只读集合属性的 C# 对象初始化 [英] C# object initialization of read only collection properties
问题描述
在我的一生中,我无法弄清楚下面的 C# 代码示例中发生了什么.测试类的集合 (List) 属性设置为只读,但我似乎可以在对象初始值设定项中分配给它.
For the life of me, I cannot figure out what is going on in the example piece of C# code below. The collection (List) property of the test class is set as read only, but yet I can seemingly assign to it in the object initializer.
** 修复了 List 'getter' 的问题
** Fixed the problem with the 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);
}
}
}
推荐答案
这个:
MyClass c = new MyClass
{
StringCollection = { "test2", "test3" }
};
翻译成这样:
MyClass tmp = new MyClass();
tmp.StringCollection.Add("test2");
tmp.StringCollection.Add("test3");
MyClass c = tmp;
它从不尝试调用 setter - 它只是根据调用 getter 的结果调用 Add
.请注意,它也不会清除原始集合.
It's never trying to call a setter - it's just calling Add
on the results of calling the getter. Note that it's also not clearing the original collection either.
这在 C# 4 规范的第 7.6.10.3 节中有更详细的描述.
This is described in more detail in section 7.6.10.3 of the C# 4 spec.
作为一个兴趣点,我对它两次调用 getter 感到有些惊讶.我希望它调用 getter 一次,然后调用 Add
两次......规范包含一个演示这一点的示例.
Just as a point of interest, I was slightly surprised that it calls the getter twice. I expected it to call the getter once, and then call Add
twice... the spec includes an example which demonstrates that.
这篇关于只读集合属性的 C# 对象初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!