小编典典

只读集合属性的C#对象初始化

c#

为了我的一生,我无法弄清楚下面的C#代码示例中发生了什么。测试类的collection(List)属性设置为只读,但是我似乎可以在对象初始化器中为其分配值。

**编辑:修复了列表’getter’的问题

using System;
using System.Collections.Generic;
using NUnit.Framework;

namespace WF4.UnitTest
{
    public class MyClass
    {
        private List<string> _strCol = new List<string> {"test1"};

        public List<string> StringCollection 
        {
            get
            {
                return _strCol;
            }
        }
    }

    [TestFixture]
    public class UnitTests
    {
        [Test]
        public void MyTest()
        {
            MyClass c = new MyClass
            {
                // huh?  this property is read only!
                StringCollection = { "test2", "test3" }
            };

            // none of these things compile (as I wouldn't expect them to)
            //c.StringCollection = { "test1", "test2" };
            //c.StringCollection = new Collection<string>();

            // 'test1', 'test2', 'test3' is output
            foreach (string s in c.StringCollection) Console.WriteLine(s);
        }
    }
}

阅读 704

收藏
2020-05-19

共1个答案

小编典典

这个:

MyClass c = new MyClass
{
    StringCollection = { "test2", "test3" }
};

译成:

MyClass tmp = new MyClass();
tmp.StringCollection.Add("test2");
tmp.StringCollection.Add("test3");
MyClass c = tmp;

它从不尝试调用setter,而只是Add在调用 getter 的结果上调用。请注意,它也不会 清除 原始集合。

C#4规范的7.6.10.3节对此进行了详细描述。

编辑:作为一个兴趣点,我有点惊讶它调用两次吸气剂。我希望它先调用getter,然后再调用Add两次…规范中包含一个演示该示例的示例。

2020-05-19