我在我的Web应用程序中使用静态只读字符串数组.基本上数组有错误代码,我已经将所有类似的错误代码保存在一个数组中并检查此数组,而不是检查每个不同的常量字符串.
喜欢
public static readonly string[] myarray = string[] {"232132132","31232132","123123123"}
Run Code Online (Sandbox Code Playgroud)
请告诉我使用静态readony字符串数组有什么害处吗?
注意:我没有遇到任何错误,想知道使用这样的是否有任何损害或性能问题?
Jes*_*lam 12
尝试这样的事情:
public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>(
new string[] {
"string1",
"string2",
"stringn",
}
);
Run Code Online (Sandbox Code Playgroud)
您需要include命名空间System.Collections.ObjectModel才能公开此对象.ReadOnlyCollection仅作为getter实现,并且您的数组内容无法更改.
正如 Ben 提到的,你的数组仍然是可修改的。它不能更改为另一个数组,但可以轻松替换其中的元素。作为替代方案,您可以将数组字段设为私有并将其公开在公共属性中,如下所示:
public class MyClass {
private static readonly string[] myArray = { ... };
private static readonly IList<string> myArrayReadOnly = Array.AsReadOnly(myArray);
public static IList<string> MyArray {
get {
return myArrayReadOnly;
}
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,你应该知道它只是数组引用是readonly,而不是数组内容.因此,如果数组是公共的(并且听起来像是这样),程序的任何部分都可以覆盖任何或所有消息,唯一不可能的是调整数组的大小.
这符合你对"伤害"的定义吗?
| 归档时间: |
|
| 查看次数: |
13389 次 |
| 最近记录: |