分配给初始化列表中的只读属性 [英] Assignment to readonly property in initializer list

查看:21
本文介绍了分配给初始化列表中的只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can one tell me, why the heck does it compile?

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

This is a nested object initializer. It's described in the C# 4 spec like this:

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

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;

这篇关于分配给初始化列表中的只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆