I am trying to do something like:
Object [] x = new Object[2];
x[0]=n开发者_JAVA百科ew Object(){firstName="john";lastName="walter"};
x[1]=new Object(){brand="BMW"};
I want to know if there is a way to achieve that inline declaration in C#
yes, there is:
object[] x = new object[2];
x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };
you were practically there, just the declaration of the anonymous types was a little off.
You can also declare 'x' with the keyword var:
var x = new
{
driver = new
{
firstName = "john",
lastName = "walter"
},
car = new
{
brand = "BMW"
}
};
This will allow you to declare your x object inline, but you will have to name your 2 anonymous objects, in order to access them. You can have an array of "x" :
x.driver.firstName // "john"
x.car.brand // "BMW"
var y = new[] { x, x, x, x };
y[1].car.brand; // "BMW"
You can also do this:
var x = new object[] {
new { firstName = "john", lastName = "walter" },
new { brand = "BMW" }
};
And if they are the same anonymous type (firstName and lastName), you won't need to cast as object
.
var y = new [] {
new { firstName = "john", lastName = "walter" },
new { firstName = "jill", lastName = "white" }
};
精彩评论