我想清理我的代碼初始化靜態只讀變量。如何使用匿名方法初始化靜態只讀變量?
原文:
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
轉換爲List<int>
?
這很奇怪,也許最好是用標準方法保存它呢? – michael
@michael也許 - 取決於你認爲更可讀和可維護的內容。這些值是不變的?你可以使用公共靜態只讀列表 MyList =新列表 {1,2,3};'? –
不,比它更多,否則內聯就會超級容易。 – michael