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

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

问题描述

有人可以告诉我,为什么会编译吗?

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;

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

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