创建一个程序,用户可以输入单词,然后弹出一个首字母缩写词,这很简单,但是我必须使用字典,并且必须使用键使首字母缩写词出现NullReferenceException不明白为什么看不到空
仅使用Visual Studio 2015,我已经尝试了很多,甚至都无法描述问题
private string fullSentence;
private string[] words = new string[5];
private Dictionary<char, string> acronymDictionary = new Dictionary<char, string>();
public Acronym(string sentence)
{
fullSentence = sentence;
string[] words = sentence.Split(' ');
}
public void BuildAcronym()
{
char[] key = new char[words.Length];
//key = null;
//foreach (string info in words)
//{
for (int i = 0; i < words.Length; i++)
{
key[i] = Convert.ToChar(words[i].Substring(0,1)); //this is where the problem is
}
我希望它能够运行,尤其是对于chars []键来说,它是由word []中每个单词的首字母填充的,因此我可以将key []设置为字典的键
答案 0 :(得分:0)
run
可以为null。
您可以在引发的行上放置一个断点,然后在“监视”窗口中检查words[i]
的值。
答案 1 :(得分:0)
请尝试这个。
private string fullSentence;
private string[] words;
private Dictionary<char, string> acronymDictionary = new Dictionary<char, string>();
public Acronym(string sentence)
{
fullSentence = sentence;
words = sentence.Split(' ');
}
public void BuildAcronym()
{
if(words != null)
{
char[] key = new char[words.Length];
//key = null;
//foreach (string info in words)
//{
for (int i = 0; i < words.Length; i++)
{
key[i] = Convert.ToChar(words[i].Substring(0,1)); //this is where the problem is
}
}
}