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)
清理:
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>?
这看起来有点奇怪,但试试这个:
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>>并调用它。
| 归档时间: |
|
| 查看次数: |
2566 次 |
| 最近记录: |