【发布时间】:2019-08-19 23:22:54
【问题描述】:
创建一个用户可以输入单词的程序,它会弹出一个首字母缩写词,这很容易,但我必须使用字典,并且键必须使我得到的首字母缩写词 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[] 由 words[] 中每个单词的第一个字母填充,因此我可以将 key[] 设置为字典的键
【问题讨论】:
-
您正在使用构造函数中具有相同名称的局部变量覆盖您的
words成员。words = sentence.Split(' '); -
哪一行代码抛出异常?
标签: c# substring nullreferenceexception