如何使用没有父类的内联变量声明内联对象

时间:2011-01-17 01:45:15

标签: c#

我正在尝试做类似的事情:

Object [] x = new Object[2];

x[0]=new Object(){firstName="john";lastName="walter"};
x[1]=new Object(){brand="BMW"};

我想知道是否有办法在C#中实现内联声明

3 个答案:

答案 0 :(得分:89)

是的,有:

object[] x = new object[2];

x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };

你几乎就在那里,只是declaration of the anonymous types稍微离开了。

答案 1 :(得分:2)

您还可以使用关键字var:

声明'x'
var x = new
{
  driver = new
  {
    firstName = "john",
    lastName = "walter"
  },
  car = new
  {
    brand = "BMW"
  }
};

这将允许您内联声明您的x对象,但您必须为您的2个匿名对象命名,以便访问它们。你可以有一个“x”数组:

x.driver.firstName // "john"
x.car.brand // "BMW"

var y = new[] { x, x, x, x };
y[1].car.brand; // "BMW"

答案 2 :(得分:1)

您也可以这样做:

var x = new object[] {
    new { firstName = "john", lastName = "walter" },
    new { brand = "BMW" }
};

如果它们是相同的匿名类型(名字和姓氏),则无需强制转换为object

var y = new [] {
    new { firstName = "john", lastName = "walter" },
    new { firstName = "jill", lastName = "white" }
};