Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 返回静态只读列表_C#_List_Static - Fatal编程技术网

C# 返回静态只读列表

C# 返回静态只读列表,c#,list,static,C#,List,Static,我有一个带有私有静态列表集合的类。现在我想返回一个只读列表。这是理想的方式吗?你会用另一种方式吗?这是正确的方法吗 namespace Test { static class Storage { private static List<string> store; static Storage() { store = new List<string>(); }

我有一个带有私有静态
列表
集合的类。现在我想返回一个只读列表。这是理想的方式吗?你会用另一种方式吗?这是正确的方法吗

namespace Test
{
    static class Storage
    {

        private static List<string> store;

        static Storage()
        {
            store = new List<string>();
        }

        //Is it okay to have a getter in my static class to return my List Collection
        public static System.Collections.ObjectModel.ReadOnlyCollection<string>getList
        {
            get
            {
                return stores.AsReadOnly();
            }
        }

        public static void addString(string add)
        {
            store.Add(add);
        }

    }
}
名称空间测试
{
静态类存储
{
私有静态列表存储;
静态存储()
{
store=新列表();
}
//在静态类中使用getter返回列表集合可以吗
公共静态System.Collections.ObjectModel.ReadOnlyCollectiongetList
{
得到
{
return stores.AsReadOnly();
}
}
公共静态void addString(字符串添加)
{
store.Add(Add);
}
}
}

这取决于客户的期望。如果你的客户希望列表的内容可以改变,那么(模糊地)没关系。如果他们期待一个不变的收藏,那么你需要一份

请注意,
List
从一开始就不是线程安全的,当进入全局可变状态时,这是一个巨大的红色警告灯,在访问时没有明显的同步


(从全局可变状态开始是一个问题,IMO,影响可测试性等。以不安全的方式这样做只会使情况变得更糟。)

除了大量不必要的换行之外,我看不出您的代码有任何错误。你在担心什么?@DStanley-你可以编辑掉这些,你知道吗?我想知道我是否正确地实现了这一点,其次,使用ReadOnlyCollection是否是返回只读列表集合的理想方式。@Oded-是的,我知道-只是发泄个人的不满:)谢谢你的警告。我会让这个线程安全吗?出于兴趣,Jon你会使用锁、ConcurrentBag或其他方法使其线程安全吗?在添加新字符串时锁定存储:Lock(store){store.Add(Add);}。