相关疑难解决方法(0)

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

对于我的生活,我无法弄清楚下面的C#代码示例中发生了什么.测试类的集合(List)属性设置为只读,但我可以在对象初始值设定项中看似分配给它.

**编辑:修复了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" …
Run Code Online (Sandbox Code Playgroud)

c# c#-3.0 c#-4.0

16
推荐指数
2
解决办法
3058
查看次数

标签 统计

c# ×1

c#-3.0 ×1

c#-4.0 ×1