2014-01-27 18 views
0

我不確定我如何使用我創建的字典,當我點擊一個按鈕,這意味着我不能從另一個函數內引用它。這可能是非常基本的,但我不記得這是如何完成的。使用一個詞典以外的空洞創建於

這是打開了一個文件對話框,然後讀取文件中的每一行按鍵,並存儲字典裏面的內容:

private void button1_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
    openFileDialog1.Filter = "Mod Pack Configuration file|*.mcf"; 
    openFileDialog1.Title = "Load Mod Pack Configuration File"; 
    openFileDialog1.ShowDialog(); 

    if (openFileDialog1.FileName != "") 
    { 
     Dictionary<string, string> loadfile = 
     File.ReadLines(openFileDialog1.FileName) 
      .Select(line => line.Split(';')) 
      .ToDictionary(parts => parts[0], parts => parts[1]); 
    } 
} 

然後後來我打開一個功能,即放置裝文件,表單內不同控件內的字符串。然而,下面的代碼does not工作作爲「loaddfile」未發現:

public void getDefaultSettings() 
{ 
    if (Properties.Settings.Default.modsDestDropDown != "") 
    { 
     modsDestDropDown.SelectedIndex = Convert.ToInt32(loadfile['modsDestDropDown']); 
    } 
} 

我可以ofcourse寫Button1的Click事件裏面的函數來代替,但因爲我在其他地方使用整個程序這個功能,它會再給我一些麻煩後

+0

你可以讓字典全球? –

回答

5

定義你的字典中class level你的方法以外這樣的:

Dictionary<string, string> loadfile; 

然後,只需初始化它在你的方法:

loadfile = File.ReadLines(openFileDialog1.FileName) 
       .Select(line => line.Split(';')) 
       .ToDictionary(parts => parts[0], parts => parts[1]); 
2

loadFile當前是僅在button1_Click範圍內可用的局部變量。如果你想讓它在多種方法中使用,你應該讓它在你的課堂上成爲一個領域。

private Dictionary<string, string> loadfile; 
private void button1_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
    openFileDialog1.Filter = "Mod Pack Configuration file|*.mcf"; 
    openFileDialog1.Title = "Load Mod Pack Configuration File"; 
    openFileDialog1.ShowDialog(); 

    if (openFileDialog1.FileName != "") 
    { 
     loadfile = 
     File.ReadLines(openFileDialog1.FileName) 
      .Select(line => line.Split(';')) 
      .ToDictionary(parts => parts[0], parts => parts[1]); 
    } 
}