相关疑难解决方法(0)

.NET 4.0中的只读列表或不可修改列表

据我所知,.NET 4.0仍然缺少只读列表.为什么框架仍然缺乏此功能?这不是域驱动设计中最常用的功能之一吗?

Java对C#的优势之一就是Collections.unmodifiablelist(list)方法的形式,它似乎早在IList <T>或List <T>中已经过期了.

使用IEnumerable<T>是问题的最简单的解决方案 - ToList可以使用并返回副本.

.net c# java readonly-collection

97
推荐指数
6
解决办法
4万
查看次数

正确公开List <T>?

我知道我不应该暴露一个List<T>属性,但我想知道这样做的正确方法是什么?例如,这样做:

public static class Class1
{
    private readonly static List<string> _list;

    public static IEnumerable<string> List
    {
        get
        {
            return _list;
            //return _list.AsEnumerable<string>(); behaves the same
        }
    }

    static Class1()
    {
        _list = new List<string>();
        _list.Add("One");
        _list.Add("Two");
        _list.Add("Three");
    }
}
Run Code Online (Sandbox Code Playgroud)

允许我的来电者简单地回到List<T>:

    private void button1_Click(object sender, EventArgs e)
    {
        var test = Class1.List as List<string>;
        test.Add("Four"); // This really modifies Class1._list, which is bad™
    }
Run Code Online (Sandbox Code Playgroud)

所以,如果我想要一个真正不可变的List<T>,我总是要创建一个新的列表?例如,这似乎有效(测试在转换后为null):

    public static IEnumerable<string> List
    {
        get
        {
            return new ReadOnlyCollection<string>(_list); …
Run Code Online (Sandbox Code Playgroud)

.net c#

12
推荐指数
2
解决办法
2599
查看次数

标签 统计

.net ×2

c# ×2

java ×1

readonly-collection ×1