gpt4 book ai didi

c# - 常量列表的内联实例化

转载 作者:IT王子 更新时间:2023-10-29 03:37:41 27 4
gpt4 key购买 nike

我试着做这样的事情:

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
};

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

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.

我该如何解决这个问题?

最佳答案

const用于编译时常量。你可以做到static readonly , 但这只适用于 METRICS变量本身(通常应该是 Metrics,按 .NET naming conventions )。它不会使 list 不可变 - 所以有人可以调用 METRICS.Add("shouldn't be here");

您可能想要使用 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 });

ReadOnlyCollection<T>只是包装了一个潜在可变的集合,但因为没有其他东西可以访问 List<T>之后,您可以将整个集合视为不可变的。

(此处的大写字母主要是猜测 - 使用更完整的名称会使它们更清晰,IMO。)

是否声明为IList<string> , IEnumerable<string> , ReadOnlyCollection<string>或者其他事情由你决定......如果你希望它应该只被视为一个序列,那么 IEnumerable<string>可能是最合适的。如果顺序很重要并且您希望人们能够通过索引访问它,IList<T>可能是合适的。如果你想让不变性变得明显,将其声明为 ReadOnlyCollection<T>可能很方便 - 但不灵活。

关于c# - 常量列表的内联实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4668365/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com