如何使用匿名方法初始化静态只读变量?

mic*_*ael 5 c# static delegates anonymous-function static-members

我正在尝试清理用于初始化静态只读变量的代码。

原来的:

public static readonly List<int> MyList;

//Initialize MyList in the static constructor
static MyObject() { ... }
Run Code Online (Sandbox Code Playgroud)


我决定清理它,因为 CodeAnalysis 说我不应该使用静态构造函数 (CA1810)。

清理:

public static readonly List<int> MyList = GetMyList();

//Returns the list
private static List<int> GetMyList() { ... }
Run Code Online (Sandbox Code Playgroud)


我真的不喜欢附加方法,所以我想我会尝试让它全部内联,但它不起作用。我不确定我在这里做错了什么......

public static readonly List<int> MyList =
    () =>
       {
           ...

           return list;
       };
Run Code Online (Sandbox Code Playgroud)

我试图将GetMyList()方法中的代码放入匿名委托中以返回要分配的列表,但它说我正在尝试将 adelegate转换为List<int>?

Jon*_*n B 6

这看起来有点奇怪,但试试这个:

public static readonly List<int> MyList = new Func<List<int>>(
() =>
{
    // Create your list here
    return new List<int>();
})();
Run Code Online (Sandbox Code Playgroud)

诀窍是创建一个新的Func<List<int>>并调用它。