【发布时间】:2017-01-13 01:00:55
【问题描述】:
例子:
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# 允许这种赋值? IMO,这没有意义,但更容易引起错误。
【问题讨论】:
-
因为匿名对象与命名对象不同。你可以把类型改成
object Bar看看... -
@Afzaal Ahmad Zeeshan:这听起来像是代码生成编译时错误的原因。然而事实并非如此。这就是问题所在。
-
你需要说
Bar = new Bar { Name = "abc" },或者在Foo说public Bar Bar {get; set;} = new Bar(); -
你拥有的是一个对象初始化器,而不是一个匿名对象。
-
相关:Property initialization does not call set for List<T>(描述了集合初始化器,但原理相同)