C#,动态对象名称?

假设我有一个对象列表

List DogList = new List(); 

我想自动添加对象,比如

  dogClass myDog1 = new dogClass(); DogList.Add(myDog1); 

那么myDog2,myDog3等等任何想法怎么做?

谢谢!

如果你不需要他们的名字,你可以试试这个。

 DogList.Add(new dogClass()); 

否则,您无法动态命名这样的变量。 但是,您可以使用字典将字符串“myDog1”等与值相关联。

C#中没有办法动态创建对象的名称(或换句话说标识符)。

所有上述解决方案都是正确的,因为它们为您创建了动态对象,而不是具有“动态名称”的动态对象。

一种可能符合您要求的迂回方式是:使用keyValue对。

例如:

 Dictionary DogList = new Dictionary(3); for(int i=1; i<=10; i++) { DogList.Add("myDog"+i,new dogClass()); } 

现在从DogList访问每个dogClass ....你可以使用 - > DogList["myDog1"]DogList["myDog5"] ......

或者如果你的dogClass有一个名为Name的属性。 名称可以用作密钥。

 List DogList = new List(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”.....呃嗯..现在我不想超越这个......当我将属性设置为:

 myName.SetIdentifierName() = "yourName"; //what happens to myName???? 

你在找这个吗?

 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()); } 

只需使用一个循环

 for(int i = 0; i<10; i++) { Doglist.add(new dogClass("puppy" + i.ToString())); } 

你为什么要那样做?

创建添加狗的方法:

 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()); }