【问题标题】:Assignment to readonly property in initializer list赋值给初始化列表中的只读属性
【发布时间】:2013-04-03 18:17:04
【问题描述】:

谁能告诉我,为什么它会编译?

namespace ManagedConsoleSketchbook
{
    public interface IMyInterface
    {
        int IntfProp
        {
            get;
            set;
        }
    }

    public class MyClass
    {
        private IMyInterface field = null;

        public IMyInterface Property
        {
            get
            {
                return field;
            }
        }
    }

    public class Program
    {
        public static void Method(MyClass @class)
        {
            Console.WriteLine(@class.Property.IntfProp.ToString());
        }

        public static void Main(string[] args)
        {
            // ************
            // *** Here ***
            // ************

            // Assignment to read-only property? wth?

            Method(new MyClass { Property = { IntfProp = 5 }});
        }
    }
}

【问题讨论】:

    标签: c# properties readonly initializer-list


    【解决方案1】:

    这是一个嵌套对象初始化器。它在 C# 4 规范中是这样描述的:

    在等号之后指定对象初始化器的成员初始化器是嵌套对象初始化器 - 即嵌入对象的初始化。嵌套对象初始值设定项中的赋值不是为字段或属性分配新值,而是被视为对字段或属性成员的赋值。嵌套对象初始化器不能应用于具有值类型的属性或具有值类型的只读字段。

    所以这段代码:

    MyClass foo = new MyClass { Property = { IntfProp = 5 }};
    

    相当于:

    MyClass tmp = new MyClass();
    
    // Call the *getter* of Property, but the *setter* of IntfProp
    tmp.Property.IntfProp = 5;
    
    MyClass foo = tmp;
    

    【讨论】:

    • 好的,现在很清楚了。不过,这是一段令人困惑的语法。
    【解决方案2】:

    因为你使用的初始化器使用了ItfProp的setter,不是Property的setter。

    所以它会在运行时抛出一个NullReferenceException,因为Property 仍然是null

    【讨论】:

    • 您能详细说明一下吗?该标准如何涵盖这种情况?
    • 等一下,启动 Visual Studio,发布一些澄清示例
    • 啊,乔恩在家里,我无法与他竞争:p
    • @Spook,别搞错了,Property 仍然是 null
    【解决方案3】:

    因为

    int IntfProp {
        get;
        set;
    }
    

    不是只读的。

    您没有调用MyClass.Property 的setter,只是调用了getter。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2014-07-17
      • 2020-04-02
      • 2014-07-30
      • 2011-10-12
      相关资源
      最近更新 更多