我已经在程序开头就宣布了一本字典
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
}
我有一个函数,使用发送的字符串填充字典
public IDictionary<string, int> SortTextIntoDictionary(string text)
{
text = text.Replace(",", ""); //Just cleaning up a bit
text = text.Replace(".", ""); //Just cleaning up a bit
text = text.Replace(Environment.NewLine, " ");
string[] arr = text.Split(' '); //Create an array of words
foreach (string word in arr) //let's loop over the words
{
if (dictionary.ContainsKey(word)) //if it's in the dictionary
dictionary[word] = dictionary[word] + 1; //Increment the count
else
dictionary[word] = 1; //put it in the dictionary with a count 1
}
return(dictionary);
}
但是我的功能还没有看到我在开始时创建的字典,我不知道如何从函数返回字典。我已经尝试将我的字典声明为静态和/或公开等,但我只是犯了更多错误。
答案 0 :(得分:5)
在班级声明你的字典:
public partial class Form1 : Form
{
public Dictionary<string, int> dictionary = new Dictionary<string, int>();
public Form1()
{
InitializeComponent();
}
}