例子:
class Foo
{
public Bar Bar { get; set; }
}
class Bar
{
public string Name { get; set; }
}
...
{
var foo = new Foo
{
Bar = { Name = "abc" } // run-time error
};
}
为什么C#允许这种赋值?在我看来,这没有意义,但更容易引起错误。
class Foo
{
public Bar Bar { get; set; } = new Bar();
}
{
var foo = new Foo
{
Bar = { Name = "abc" } // no error
};
}
实际上这并不是匿名对象,而是使用对象初始化器语法。
{
var foo = new Foo
{
Bar = { Name = "abc" } // run-time error
};
}
{
var foo = new Foo();
foo.Bar = new Bar { Name = "abc" }; // Fine, obviouslly
foo.Bar = { Name = "abc" }; // compile error
}
使用对象初始化程序语法后,对象名称变得多余,因为它已经知道了。
object Bar
并查看... - Afzaal Ahmad ZeeshanBar = new Bar { Name = "abc" }
,或者在Foo
中说public Bar Bar { get; set; } = new Bar();
。 - Wagner DosAnjos