加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在初始化列表中分配readonly属性

发布时间:2020-12-16 00:07:23 所属栏目:百科 来源:网络整理
导读:可以告诉我,为什么它会编译? namespace ManagedConsoleSketchbook{ public interface IMyInterface { int IntfProp { get; set; } } public class MyClass { private IMyInterface field = null; public IMyInterface Property { get { return field; } } }
可以告诉我,为什么它会编译?

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读