如何创建常量静态数组?

jp2*_*ode 0 c# class

我有一个我的数据库的静态字符串类,所以我总是拼写他们设计的表和列.

我目前在这一个类中有大约500行代码,但这是一个简短的例子:

public const string PURCHASING = "PURCHASING";
public const string SCHED_PURCH = "SCHED/PURCH";
public const string SCHEDULING = "SCHEDULING";
Run Code Online (Sandbox Code Playgroud)

要创建"Clerk"部门的只读静态字符串数组,我使用此静态声明:

public static string[] CLERK_DEPT {
  get {
    return new string[] { PURCHASING, SCHEDULING, SCHED_PURCH };
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的数据库字符串类中有许多这样的代码行.

今天,我遇到了这个活跃的帖子,有人做了非常相似的事情:

如何防止修改类中的私有字段?

答案提供了一种方法来提供我以前没有考虑过的只读字符串数组:

您必须返回阵列的副本.

public String[] getArr() {
  return arr == null ? null : Arrays.copyOf(arr, arr.length);
}
Run Code Online (Sandbox Code Playgroud)

这让我想知道,如果有人在这里知道更有效的方式传回我的只读字符串数组.

我必须承认,我总是憎恶return new string[]我的代码中的想法.

那么,有吗?...一种更有效,更清洁的方式,或者我已经创建了最佳解决方案?

Jon*_*eet 6

基本上没有不可变数组这样的东西.

如果你信任所有的调用者,你可以告诉他们不要改变数组.另一种方法是提供只读包装:

private static readonly ReadOnlyCollection<string> clerkDepartments =
    new ReadOnlyCollection<string>(
        new[] { "PURCHASING", "SCHED/PURCH", "SCHEDULING" });

public static readonly ReadOnlyCollection<string> ClerkDepartments
    { get { return clerkDepartments; } }
Run Code Online (Sandbox Code Playgroud)

请注意,虽然ReadOnlyCollection<T>不是一个完全不可变的集合,但只有访问底层集合的代码才能改变它 - 并且因为唯一"知道"数组的代码是将它传递给构造函数的初始化程序,所以基本上是安全的除非有人破解反射:)