c# - 分配给初始化列表中的只读属性

标签 c# properties readonly initializer-list

有人能告诉我,它到底为什么要编译吗?

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# 4 规范中是这样描述的:

A member initializer that specifies an object initializer after the equals sign is a nested object initializer - that is, an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type.

所以这段代码:

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;

关于c# - 分配给初始化列表中的只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15784483/

相关文章:

typescript - 以嵌套方式将界面中的所有字段设为只读

javascript - 在 JavaScript 中使原始数据类型只读/非配置

C#:IFormattable、IFormatProvider 和 ICustomFormatter 之间的连接,以及何时使用什么

c# - 我无法让我的最后一个索引成为第一个索引 C#

JavaFX 使用非 JavaFX 线程的 UI 中使用的提取器更新 ObservableList

c# - 防止继承成员访问 protected 成员

qt - "file.open(QIODevice::ReadOnly)"是什么意思?

c# - 每个 'await' 运算符都会产生一个状态机吗?

c# - Mjpeg 流式传输不适用于谷歌浏览器

cocoa - 获取 ABPerson 属性的标签名称