我正在开发一个需要创建许多对象的项目。 我想将对象称为player1,player2,player3等。
Class Player
{
public string Name { get; set; }
public List<string> NotPlayedAgainst { get; set; }
public List<string> NotPlayedWith { get; set; }
public int PositivePoints { get; set; }
public int NegativePoints { get; set; }
}
现在通过重复以下代码来创建对象:
int x = 1;
Player player(x) = new Player();
x++;
我需要能够在代码中稍后使用规则调用对象。 所以我也想知道如何使用这样的规则来调用这些对象:
player(x).Name = /*some code*/
答案 0 :(得分:2)
将这些对象添加到Id
并通过索引或(根据您的实际要求)访问它们提供标识对象的属性,例如class Object
{
public Object(int id)
{
this.Id = id;
}
public int Id { get;}
}
:
List<Object> objectList = new List<Object>();
for(int id = 1; id <= 10; id++)
{
Object objectX = new Object(id);
objectList.Add(objectX);
}
或两者:
DocuSignAPI.Tab tab100 = new DocuSignAPI.Tab() ;
tab100.Type_x = 'Custom' ;
tab100.RecipientID = 1 ;
tab100.DocumentID = 1 ;
tab100.PageNumber = 1 ;
tab100.XPosition = 40 ;
tab100.YPosition = 40 ;
答案 1 :(得分:1)
你有很多方法......
列表方法:
class Program
{
static void Main(string[] args)
{
List<Dog> dogs = new List<Dog>();
for(int i=0; i < 100; i++)
{
dogs.Add(new Dog());
}
Dog firstDog = dogs[0];
}
}
class Dog
{
}
数组方法:
class Program
{
static void Main(string[] args)
{
Dog[] dogs = new Dog[100];
for(int i=0; i < 100; i++)
{
dogs[i] = new Dog();
}
Dog firstDog = dogs[0];
}
}
class Dog
{
}
字典方法:
class Program
{
static void Main(string[] args)
{
Dictionary<int, Dog> dogs = new Dictionary<int, Dog>();
for(int i=0; i < 100; i++)
{
dogs.Add(i, new Dog());
}
Dog firstDog = dogs[0];
}
}
class Dog
{
}
答案 2 :(得分:0)
使用Dictionary<key, value>
:
Dictionary<string, object> objects = new Dictionary<string, object>();
for (int i = 0; i < 5; i++)
{
objects.Add("obj" + i, new object());
}
并访问索引2的对象:
object myObj = objects["obj2"];