2011-10-12 65 views
2

我有一個抽象類,並想爲錯誤代碼添加靜態字典。我嘗試了以下內容:C#靜態字典在抽象類中聲明和初始化.NET 2.0

public abstract class Base 
{ 
    ... 
    protected static readonly Dictionary<int, string> errorDescriptions = new Dictionary<int, string>() 
    { 
     { 1, "Description1"}, 
     { 2, "Description2"}, 
     ... 
    }; 
    ... 
} 

但後來發現這是在.NET 3.0中實現的;我使用2.0。我環顧四周,還有人建議我在構造函數中添加對,但這是一個抽象類。

如何填寫字典?

謝謝。

+0

ctor怎麼樣? – asawyer

回答

7
public abstract class Base 
{ 
    ... 
    protected static readonly Dictionary<int, string> errorDescriptions; 
    // Type constructor called when Type is first accessed. 
    // This is called before any Static members are called or instances are constructed. 
    static Base() 
    { 
     errorDescriptions = new Dictionary<int, string>(); 
     errorDescriptions[1] = "Description1"; 
     errorDescriptions[2] = "Description2"; 
    } 
} 
+0

謝謝,只是幾個跟進問題。因此,如果派生類DerivedClass使用字典DerivedClass.errorSescriptions,程序首先調用Base()。或者它僅在派生類被創建時使用,「public DerivedClass(,,):base(){...}'?構造函數是靜態的嗎? – john

+0

單個字典已創建並可供所有子類使用。是的,它在任何子類被使用之前被實例化。 –

+0

如果'Base'具有其他非靜態字段,構造函數不應該是靜態正確的? – john