【问题标题】:why does it give me a NullReferenceException yet no errors为什么它给我一个 NullReferenceException 但没有错误
【发布时间】: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[] 设置为字典的键

【问题讨论】:

标签: c# substring nullreferenceexception


【解决方案1】:

请试试这个。

    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
            }
         }
     }

【讨论】:

    【解决方案2】:

    words[i] 可以为空。

    您可以在抛出的行上放置一个断点,然后在“观察”窗口中检查words[i] 的值。

    【讨论】:

      猜你喜欢
      • 2016-09-18
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多