2013-01-23 160 views
3

我想知道如何聲明/初始化字典? 下面的錯誤。初始化字典<字符串,列表<string>>

Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>() 
{ 
    {"tab1", MyList } 
}; 

List <string> MyList = new List<string>() { "1" }; 

錯誤是:字段初始值設定項無法引用非靜態字段,方法或屬性MyList。字典之前或之後不是List聲明。

+0

http://stackoverflow.com/a/14472283/922198 –

+0

「給出了一個錯誤」。涼。謹慎分享錯誤? :/ –

+3

如果這些是實例字段,則不能單獨使用字段初始值設定項來完成。您必須在構造函數中初始化字典。 –

回答

4

正如Scott張伯倫在his answer說:

如果這些非靜態字段定義,你不能使用領域 初始化這樣的,你必須把數據在構造函數中。

class MyClass 
{ 
    Dictionary<string, List<string>> myD;   
    List <string> MyList; 

    public MyClass() 
    { 
     MyList = new List<string>() { "1" }; 
     myD = new Dictionary<string, List<string>>() 
     { 
      {"tab1", MyList } 
     }; 
    } 
} 

此外,對於靜態字段

private static List<string> MyList = new List<string>() 
{  
    "1" 
}; 

private static Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>() 
{ 
    {"tab1", MyList } 

}; 
+0

..這是不正確的。看到這個:http://stackoverflow.com/a/14472392/1517578 –

+0

@SimonWhitehead - 固定thnx! –

4

如果這些非靜態字段定義,你不能使用字段初始這樣,你必須把數據在構造函數中。

class MyClass 
{ 
    Dictionary<string, List<string>> myD;   
    List <string> MyList; 

    public MyClass() 
    { 
     MyList = new List<string>() { "1" }; 
     myD = new Dictionary<string, List<string>>() 
     { 
      {"tab1", MyList } 
     }; 
    } 
} 
3
Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>() 
{ 
    {"tab1", new List<string> { "1" } }, 
    {"tab2", new List<string> { "1","2","3" } }, 
    {"tab3", new List<string> { "one","two" } } 
}; 
相關問題