【问题标题】:Why does C# allow to assign anonymous object to class fields which are of class types?为什么 C# 允许将匿名对象分配给类类型的类字段?
【发布时间】: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" },或者在Foopublic Bar Bar {get; set;} = new Bar();
  • 你拥有的是一个对象初始化器,而不是一个匿名对象。
  • 相关:Property initialization does not call set for List<T>(描述了集合初始化器,但原理相同)

标签: c# .net


【解决方案1】:

这之所以成为可能,是因为如果对象已经被实例化,它不会导致运行时错误。

class Foo
{
    public Bar Bar { get; set; } = new Bar();
}

{
    var foo = new Foo
    {
        Bar = { Name = "abc" } // no error
    };
}

【讨论】:

  • 您的意思是“实例化”。显然,新表达式是试图初始化 Bar 实例的表达式。它只需要一个实例开始,不管它是否被作者的定义初始化。
【解决方案2】:

这其实不是匿名对象,而是使用object initializer语法。

{
    var foo = new Foo
    {
        Bar = { Name = "abc" } // run-time error
    };
}

上面的sn-p其实和下面说的一样:

{
    var foo = new Foo();
    foo.Bar = new Bar { Name = "abc" }; // Fine, obviouslly
    foo.Bar = { Name = "abc" }; // compile error
}

对象名称变得多余,因为使用对象初始值设定项语法已经知道它。

【讨论】:

    猜你喜欢
    • 2017-09-08
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多