内联实例化常量List

Rof*_*ion 90 .net c#

我尝试做这样的事情:

public const List<String> METRICS = new List<String>()
        {
            SourceFile.LOC,
            SourceFile.MCCABE,
            SourceFile.NOM,
            SourceFile.NOA,
            SourceFile.FANOUT,
            SourceFile.FANIN,
            SourceFile.NOPAR,
            SourceFile.NDC,
            SourceFile.CALLS
        };
Run Code Online (Sandbox Code Playgroud)

但不幸的是,这不起作用:

FileStorer.METRICS' is of type 'System.Collections.Generic.List<string>'. A const field of a reference type other than string can only be initialized with null.
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

Jon*_*eet 173

const用于编译时常量.您可以创建它static readonly,但这只适用于METRICS变量本身(通常应该是Metrics,而不是.NET命名约定).它不会使列表不可变 - 所以有人可以打电话METRICS.Add("shouldn't be here");

你可能想用a ReadOnlyCollection<T>来包装它.例如:

public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
    (new List<String> { 
         SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
         SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn, 
         SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });
Run Code Online (Sandbox Code Playgroud)

ReadOnlyCollection<T>只包装一个潜在的可变集合,但由于没有其他任何东西可以访问List<T>后来,你可以认为整个集合是不可变的.

(这里的大写主要是猜测 - 使用更全面的名称会让他们更清楚,IMO.)

无论你把它声明为IList<string>,IEnumerable<string>,ReadOnlyCollection<string>或别的东西,是你......如果你期望它应该只作为一个序列来处理,那么IEnumerable<string>很可能是最合适的.如果订单很重要并且您希望人们能够通过索引访问它,则IList<T>可能是合适的.如果你想使不变性显而易见,宣布它ReadOnlyCollection<T>可能很方便 - 但不灵活.

  • 我来这里是为了寻找 `new List&lt;string&gt;{ ... }` 部分。谢谢乔恩:) (2认同)

Luk*_*keH 21

您需要使用static readonly列表.如果您希望列表是不可变的,那么您可能需要考虑使用ReadOnlyCollection<T>而不是List<T>.

private static readonly ReadOnlyCollection<string> _metrics =
    new ReadOnlyCollection<string>(new[]
        {
            SourceFile.LOC,
            SourceFile.MCCABE,
            SourceFile.NOM,
            SourceFile.NOA,
            SourceFile.FANOUT,
            SourceFile.FANIN,
            SourceFile.NOPAR,
            SourceFile.NDC,
            SourceFile.CALLS
        });

public static ReadOnlyCollection<string> Metrics
{
    get { return _metrics; }
}
Run Code Online (Sandbox Code Playgroud)