[英]C#, dynamic object names?
假设我有一个对象列表
List<dogClass> DogList = new List<dogClass>();
我想自动向它添加对象,比如
dogClass myDog1 = new dogClass();
DogList.Add(myDog1);
然后是 myDog2、myDog3 等。有什么想法可以做到吗?
在 C# 中没有办法动态创建对象的名称(或换句话说标识符)。
上面给出的所有解决方案在某种意义上都是正确的,它们为您创建了动态对象,而不是具有“动态名称”的动态对象。
可能符合您要求的一种迂回方式是:使用 keyValue 对。
例如:
Dictionary<string, dogClass> DogList = new Dictionary<string, dogClass>(3);
for(int i=1; i<=10; i++)
{
DogList.Add("myDog"+i,new dogClass());
}
现在从 DogList 访问这些 dogClass 中的每一个……你可以使用-> DogList["myDog1"]
或DogList["myDog5"]
......
或者如果您的 dogClass 有一个名为 Name 的属性。 Name 可以用作 Key。
List<dogClass> DogList = new List<dogClass>(3);
for(int i=1; i<=10; i++)
{
DogList.Add(new dogClass(Name:"myDog"+i));
}
GetDogWithName("myDog1"); //this method just loops through the List and returns the class that has the Name property set to myDog1
在这里,对于普通人或外行来说……您已经创建了具有唯一名称的对象。 但是对于你和我......它们是字符串而不是对象的名称。
一个更有趣的想法......如果 C# 给了我们一个函数(或属性)是这样的:
int myName = 0;
现在如果myName.GetIdentifierName()
返回“myName”..... uhhhh .. 现在我不想考虑这个.....当我将属性设置为时会发生什么:
myName.SetIdentifierName() = "yourName"; //what happens to myName????
只需使用循环
for(int i = 0; i<10; i++)
{
Doglist.add(new dogClass("puppy" + i.ToString()));
}
你在找这个吗?
for(int i =0; i<100;i++){
DogList.Add(new dogClass());
}
您不必先将它们存储在变量中:
DogList.Add(new DogClass());
没问题。
如果要添加多个:
DogList.Add(new DogClass());
DogList.Add(new DogClass());
DogList.Add(new DogClass());
或者,如果您想要这种灵活的方式:
for(int i = 0; i < NR_OF_OBJECTS_TO_ADD; i++) {
DogList.Add(new DogClass());
}
你为什么要这样做?
创建一个添加狗的方法:
void AddDog()
{
DogList.Add(new dogClass());
}
并通过索引访问它们:
dogClass GetDog(Int32 index)
{
return DogList[index];
}
for (int i = 0; i < 10; i++)
{
dogClass myDog = new dogClass();
DogList.Add(myDog);
}
我不确定你的意图是什么,但也许你想循环:
for(int i = 0; i < 10; i++)
{
dogList.Add(new DogClass());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.