20 c# wcf readonly readonly-collection
我跑了一名安全码分析师,发现自己有一个CA2105警告.我查看了等级篡改示例.我没有意识到你可以将int []分配给readonly int.我认为readonly就像C++ const并使其成为非法的.
如何修复违规建议我克隆对象(我不想做)或'用无法更改的强类型集合替换数组'.我点击了链接并看到'ArrayList'并逐个添加每个元素,看起来你不能阻止添加更多内容.
所以,当我有这段代码时,最简单或最好的方法是什么才能使它成为只读集合?
public static readonly string[] example = { "a", "b", "sfsdg", "sdgfhf", "erfdgf", "last one"};
Run Code Online (Sandbox Code Playgroud)
Mik*_*son 36
拥有一个无法修改的集合的最简单方法是使用
来自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);
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 11
public static readonly ReadOnlyCollection<string> example
= new ReadOnlyCollection<string>(new string[] { "your", "options", "here" });
Run Code Online (Sandbox Code Playgroud)
(虽然它仍然可能作为get财产而不是公共领域暴露)
如果您正在使用数组,则可以使用
return Array.AsReadOnly(example);
Run Code Online (Sandbox Code Playgroud)
将数组包装在只读集合中.
| 归档时间: |
|
| 查看次数: |
21154 次 |
| 最近记录: |