我正在尝试清理用于初始化静态只读变量的代码。
原文:
public static readonly List<int> MyList;
//Initialize MyList in the static constructor
static MyObject() { ... }
我决定清理它,因为 CodeAnalysis 说我不应该使用静态构造函数 (CA1810)。
清理:
public static readonly List<int> MyList = GetMyList();
//Returns the list
private static List<int> GetMyList() { ... }
我不太喜欢额外的方法,所以我想我会尝试让它全部内联,但它不会起作用。我不确定我在这里做错了什么......
public static readonly List<int> MyList =
() =>
{
...
return list;
};
我试图获取 GetMyList()
中的代码方法并将其放在匿名委托(delegate)中以返回要分配的列表,但它说我正在尝试转换 delegate
进入 List<int>
?
最佳答案
这看起来有点奇怪,但试试这个:
public static readonly List<int> MyList = new Func<List<int>>(
() =>
{
// Create your list here
return new List<int>();
})();
诀窍是创建一个新的 Func<List<int>>
并调用它。
关于c# - 如何使用匿名方法初始化静态只读变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13570268/