我剛剛收到一個異常,當我嘗試在另一個類中引用一個靜態變量時,它也被靜態初始化。這在之前有效,並且由於某種原因,現在它失敗了。我所做的唯一更改是將Visual Studio(2010)重置爲其默認設置,這是我無法想象的原因。我添加的任何其他代碼也沒有觸及任何受影響的部分。TypeInitializationException/ArgumentException當引用初始化變量時
這是我的代碼
的WinForms類 '的MainForm':
partial class MainForm : Form
{
// ...
private RefClass convMan;
private Dictionary<EnumType, string> LogNames = RefClass.LogNames;
// ...
public MainForm() { .... }
}
引用的類 'RefClass':
class RefClass
{
// ...
public enum EnumType { TypeOne = 0, TypeTwo = 1, TypeThree = 2 };
public static Dictionary<EnumType, string> LogNames = new Dictionary<EnumType, string>()
{
{ EnumType.TypeOne, "Text0" },
{ EnumType.TypeTwo, "Text1" },
{ EnumTypy.TypeThree, "Text2" }
};
}
我現在得到錯誤的是(從翻譯德語):
An unhandled exception of type "System.TypeInitializationException" occurred.
Additional information: The type initializer for "RefClass" threw an exception.
它具有的InnerException
System.ArgumentException
所以,就我個人而言,一旦它進入我的靜態辭典應該被初始化,因此當我Form類引用它。我嘗試調試,以查看靜態字典是否在Form類中引用之前被初始化,但情況並非如此。另外,當我停在參考線的斷點處時,變量LogNames爲空。
我真的很困惑,爲什麼發生這種情況,這一切都工作過。
我找到了解決方案,當stackoverflow允許我這樣做時,我會自己回答。無論如何謝謝大家! – Yeehaw
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –