我运行了一个安全代码分析师,我发现自己有一个 CA2105警告. 。我看了篡改榜样。我没有意识到您可以将int []分配给可读的int。我认为Readonly就像C ++ const,使其成为非法。

如何解决违规行为表明我克隆了对象(我不想这样做)或“用无法更改的强大键入集合替换数组”。我单击了链接,然后查看“ arraylist”并逐一添加每个元素,看起来您无法阻止添加更多内容。

因此,当我拥有此代码时,最简单或最佳的方法是使其仅阅读收藏?

public static readonly string[] example = { "a", "b", "sfsdg", "sdgfhf", "erfdgf", "last one"};
有帮助吗?

解决方案

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

READONLYCOLLECTY

来自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);

其他提示

public static readonly ReadOnlyCollection<string> example
    = new ReadOnlyCollection<string>(new string[] { "your", "options", "here" });

(尽管它仍然应该被暴露为 get 财产而不是公共场)

如果您正在使用数组,则可以使用

return Array.AsReadOnly(example);

将您的数组包裹在只读的集合中。

var readOnly = new ReadOnlyCollection<string>(example);
ReadOnlyCollection<string> readOnlyCollection = 
            new ReadOnlyCollection<string>(example);

我当时正在寻找类似的解决方案,但是我仍然希望能够从班级内部修改集合,因此我选择了此处概述的选项:http://www.csharp-examples.net/readonly-collection/

简而言之,他的例子是:

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

    public IList<int> Items
    {
        get { return _items.AsReadOnly(); }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top