如何生成对象名称
本文关键字:对象 何生成 | 更新日期: 2023-09-27 18:24:09
如何生成对象名称?例如:
ObjectEx "name" = new ObjectEx();
编辑:
该对象将由用户输入命名。代码为:
Console.Write("Input new user's name: ");
string newUsersName = Console.ReadLine();
(Create ObjectEx)
第2版:
我有一个用于ObjectEx
(Person
)的Dictionary
,它处理所有ObjectEx
s。
Person
是真正的类名,很抱歉制作示例对象ObjectEx
。
public static List<Person> persons = new List<Person>();
对象没有名称-变量有,并且它们总是在编译时确定的。
如果您想要从字符串到对象的映射,只需使用Dictionary<string, ObjectEx>
,然后使用Random
附带随机字符串。(有很多在Stack Overflow上生成随机字符串的例子。)
如果你只想要一个对象集合,并且你使用"随机名称"来表达,那么使用List<ObjectEx>
——在这种情况下,你根本不需要名称。
如果你需要其他东西,请更具体一些。
您可以使用array
并将对象存储在其中。
ObjectEx []arrObjectEx = new ObjectEx[10];
arrObjectEx[0] = new ObjectEx();
如果随机元素的数量未知,我会使用list<T>
(泛型列表)而不是数组。
List<ObjectEx> lstObjectEx = new List<ObjectEx>();
lstObjectEx.Add(new ObjectEx());
若随机生成的对象需要唯一访问,那个么可以使用dictionary。例如
Dictionary<int, ObjectEx> dicObjectEx = new Dictionary<int, ObjectEx>();
dicObjectEx.Add(someUniqueNumber, new ObjectEx());
这是不可能的,但使用字典怎么样。您可以使用字符串值Add并获取存储的对象。
// somewhere near the start in your code initialize the dictionary
var dict = new Dictionary<string, Person>();
// later on you can dynamically add an Object to the Dictionary
// newUsersName is the so called Index
string newUsersName = Console.ReadLine();
dict.Add(newUsersName, new Person());
// if you need to get hold of that object again use the Index
// myObj is a Person type
var myObj = dict[newUsersName];
// assume Person has an Age property
myObj.Age = 20;
// show all Persons now in the dictionary
foreach(var username in dict.Keys)
{
Console.WriteLine(username);
var pers = dict[username];
Console.WriteLine("{0} is {1} years old", username, pers.Age );
}
您可以使用字典来存储对象,其中Key是对象名称