C# 什么是只读集合?

C# 什么是只读集合?,c#,wcf,readonly,readonly-collection,C#,Wcf,Readonly,Readonly Collection,我运行了一个安全代码分析师,我发现自己有一个问题。我看了一个等级篡改的例子。我不知道你可以将int []分配给一个只读int。我认为Read OnLee就像C++ const,使它非法。 “如何修复冲突”建议我克隆对象(我不想这样做)或“用无法更改的强类型集合替换数组”。我点击了链接,看到了“ArrayList”并一个接一个地添加了每个元素,看起来你无法阻止添加更多的元素 那么,当我有了这段代码时,让它成为只读集合的最简单或最好的方法是什么 public static readonly stri

我运行了一个安全代码分析师,我发现自己有一个问题。我看了一个等级篡改的例子。我不知道你可以将int []分配给一个只读int。我认为Read OnLee就像C++ const,使它非法。 “如何修复冲突”建议我克隆对象(我不想这样做)或“用无法更改的强类型集合替换数组”。我点击了链接,看到了“ArrayList”并一个接一个地添加了每个元素,看起来你无法阻止添加更多的元素

那么,当我有了这段代码时,让它成为只读集合的最简单或最好的方法是什么

public static readonly string[] example = { "a", "b", "sfsdg", "sdgfhf", "erfdgf", "last one"};
var readOnly=new ReadOnlyCollection(示例);
公共静态只读只读只读收集示例
=新的ReadOnlyCollection(新字符串[]{“您的”、“选项”、“此处”});
(尽管它可能仍应作为
get
属性而不是公共字段公开)

ReadOnlyCollection ReadOnlyCollection=
新的只读集合(示例);

拥有无法修改的集合的最简单方法是使用

MSDN中的示例:

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

ReadOnlyCollection<string> readOnlyDinosaurs = new ReadOnlyCollection<string>(dinosaurs);
列出恐龙=新列表();
恐龙。添加(“暴龙”);
恐龙。添加(“Amargasaurus”);
恐龙。添加(“Deinonychus”);
恐龙。添加(“Compsognatus”);
ReadOnlyCollection readOnlyDinosaurs=新的ReadOnlyCollection(恐龙);

如果使用阵列,可以使用

return Array.AsReadOnly(example);

将数组包装为只读集合。

我正在寻找类似的解决方案,但我希望仍然能够从类内部修改集合,因此我选择了此处列出的选项:

简言之,他的例子是:

public class MyClass
{
    private List<int> _items = new List<int>();

    public IList<int> Items
    {
        get { return _items.AsReadOnly(); }
    }
}
公共类MyClass
{
私有列表_items=新列表();
公共物品
{
获取{return _items.AsReadOnly();}
}
}

readOnlyCollection=Normal collection-Add/remove api-Set indexer的可能重复项我将在这里再次使用变量的
readonly
关键字。如果没有这一点,任何人都可能会产生这样的印象,即由于集合的类型为
ReadOnlyCollection
,因此我完全可以避免对我的集合进行任何可能的更改。您可能没有意识到集合是只读的,但指向它的变量不是。如果我可以将变量本身重新分配给一个新的集合,那么
ReadOnlyCollection
将意味着什么+1.@RBT注意只读是一个谎言;只读字段绝对可以进行变异。当然,你得有点作弊……我花了一段时间才消化。谢谢你给我指路。
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

ReadOnlyCollection<string> readOnlyDinosaurs = new ReadOnlyCollection<string>(dinosaurs);
return Array.AsReadOnly(example);
public class MyClass
{
    private List<int> _items = new List<int>();

    public IList<int> Items
    {
        get { return _items.AsReadOnly(); }
    }
}