0

如何修改以下代码:

var people = new[] {
   new { name = "John", surname = "Smith" },
   new { name = "John", surname = "Doe" },
};

不使用var关键字(所以我可以在对象初始化程序中初始化变量)并且仍然能够访问这样的元素?:

System.Console.WriteLine(people[0].surname); //John
System.Console.WriteLine(people[1].surname); //Doe
4

4 回答 4

5

You cannot; you will have to define a proper class for these objects or reuse one (e.g. Tuple).

Technically the one-word change from var to dynamic will also do the trick, but of course this changes the essence of the member dramatically so it's not equivalent by any stretch of the imagination.

于 2013-01-23T15:25:17.850 回答
5

Define a model:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

and then have a collection of this model:

List<Person> people = new List<Person>();
people.Add(new Person { Name = "John", Surname = "Smith" });
people.Add(new Person { Name = "John", Surname = "Doe" });

or:

var people = new List<Person> 
{ 
    new Person { Name = "John", Surname = "Smith" }, 
    new Person { Name = "John", Surname = "Doe" } 
};

and then you can still:

System.Console.WriteLine(people[0].Surname); //John
System.Console.WriteLine(people[1].Surname); //Doe
于 2013-01-23T15:25:18.603 回答
2

首先,您需要为该数据创建一个命名类型:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

然后在创建数组时使用该类型:

People[] people;

//...

people = new People[]{
    new Person{ Name = "John", Surname = "Smith" },
    new Person{ Name = "John", Surname = "Doe" },
};
于 2013-01-23T15:27:06.417 回答
1

You could use 'dynamic'

dynamic people = new[] {
   new { name = "John", surname = "Smith" },
   new { name = "John", surname = "Doe" },
};

And then call it

Console.WriteLine(people[0].name);

Note - Works on framework 4.0 onwards, also comes with the caveats mentioned already.

于 2013-01-23T15:30:22.660 回答