优雅分配静态只读字符串集合

时间:2012-01-30 09:51:32

标签: c# .net

我想创建一个带字符串的静态ReadOnlyCollection

有什么方法可以让这个表达更短或更优雅?

public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>(
  new string[] {
    "string1",
    "string2",
    "string3",
  }
);

我多次使用它,但是在不同的文件中。

5 个答案:

答案 0 :(得分:14)

另一种选择是将List<T>与集合初始值设定项和AsReadOnly方法一起使用:

public static readonly ReadOnlyCollection<string> ErrorList = new List<String> {
    "string1",
    "string2",
    "string3",
  }.AsReadOnly();

答案 1 :(得分:10)

public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>(
  new [] {
    "string1",
    "string2",
    "string3"
  }
);

答案 2 :(得分:2)

我认为最紧凑的是:

using StringCol = ReadOnlyCollection<string>;
...
public static readonly StringCol ErrorList = new StringCol(
      new[]
      {
        "string1",
        "string2",
        "string3",
      });

using指令就是为了减少代码量,以防你大量使用ReadOnlyCollection<string>。如果不是这样,它就不会减少任何东西。

答案 3 :(得分:1)

Array.AsReadOnly<T>new[]可以推断出数组的内容:

public static readonly ReadOnlyCollection<string> ErrorList = Array.AsReadOnly(
  new[] {
    "string1",
    "string2",
    "string3",
  }
);

如果您不介意使用界面,ReadOnlyCollection<T> implements several of them包括IList<T>

public static readonly IList<string> ErrorList = Array.AsReadOnly(
  new[] {
    "string1",
    "string2",
    "string3",
  }
);

在风格上,我更喜欢避免单个块的多个缩进:

public static readonly IList<string> ErrorList = Array.AsReadOnly(new[] {
  "string1",
  "string2",
  "string3",
});

答案 4 :(得分:0)

我想到了另一种可能性,通过结合本文中的一些重要答案。

使用params创建自定义方法:

    public static ReadOnlyCollection<String> CreateStringsReadOnlyCollection(params  string[] st){

        return new ReadOnlyCollection<String>(st);
    }

然后使用它:

 public readonly static ReadOnlyCollection<String> col = CreateStringsReadOnlyCollection("string1", "string2", "string3");