为什么集合初始化忽略访问修饰符?初始化、修饰符

2023-09-06 15:12:44 作者:无人能懂的悲伤

Spawing从这个答案,一些code看来,似乎没有什么意义:

Spawing from this answer, some code appeared that seems to not make sense:

class Program
{
    static void Main(string[] args)
    {
        var t = new Testing
        {
            ListOfStrings =
            { 
                "hello", 
                "goodbye" 
            }
        };

        Console.ReadKey();
    }
}

public class Testing
{
    public List<string> ListOfStrings { get; private set; }

    public Testing()
    {
        ListOfStrings = new List<string>();
    }
}

乍一看人会认为这code就不能编译:所有的 ListOfStrings 应该后有一个私人二传手,而不应是能以这种方式被分配给

At first glance one would think this code wouldn't compile: after all ListOfStrings is supposed to have a private setter, and shouldn't be able to be assigned to in this manner.

然而,这code编译并运行良好,而 t.ListOfStrings 已分配的值。

However, this code compiles and runs fine, and t.ListOfStrings has the values assigned.

为什么这个集合初始化忽略了私人二传手?

Why does this collection initialization ignore the private setter?

推荐答案

在您的例子中,你实际上并没有设置该属性。

In your example you are not actually setting the property.

C#是足够聪明,知道你正在使用的ICollection可以使用添加,删除公开修改,清除等你在做什么是此等价的:

C# is smart enough to know that you are using an ICollection which can be publicly modified using Add, Remove, Clear, etc. What you are doing is the equivalent of this:

t.AddRange(new string[] { "hello", "goodbye" });

如果你真的想做到这一点是行不通的:

If you actually tried to do this it would not work:

var t = new Testing
{
    ListOfStrings = new List<string>(),
};

编辑:

因为你可能想知道如何公开集合为只读,您可以通过只露出它作为一个IEnumerable做到这一点:

Since you might be wondering how to expose a collection as readonly, you can do this by just exposing it as an IEnumerable:

public class Testing
{
    private List<string> _listOfStrings;
    public IEnumerable<string> MyStrings
    {
        get
        {
            foreach (var s in _myStrings)
                yield return s;
        }
    }

    public Testing()
    {
        _listOfStrings = new List<string>();
    }
}

您也可以创建一个只读的集合,但我觉得这是比较混乱的。如果将其公开为IEnumerable那么消费者的类可以通过与没有能力添加或删除项目的项目一一列举。

You could also create a readonly collection but I find that is more confusing. If you expose it as IEnumerable then consumers of the class can enumerate through the items with no ability to add or remove items.

 
精彩推荐