首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >常量列表的内联实例化

常量列表的内联实例化
EN

Stack Overflow用户
提问于 2011-01-12 19:44:02
回答 2查看 122.3K关注 0票数 108

我试着这样做:

代码语言:javascript
复制
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
        };

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

代码语言:javascript
复制
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.

我该如何解决这个问题?

EN

回答 2

Stack Overflow用户

发布于 2011-01-12 19:45:14

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

代码语言:javascript
复制
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; }
}
票数 26
EN

Stack Overflow用户

发布于 2019-03-28 22:43:46

您正在寻找一个简单的代码,如下所示:

代码语言:javascript
复制
    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });
票数 -10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4668365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档