数组元素被认为是空的,即使它在使用拆分方法时显然不是?

Array element is considered null even though it clearly isn't when using the split method?

提问人:Elijah.S 提问时间:7/30/2020 最后编辑:Alexei LevenkovElijah.S 更新时间:7/30/2020 访问量:51

问:

我正在尝试仅使用数字格式化电话号码,因此我使用的是 Split 方法。但是,Visual Studio 声明电话号码存储变量 readName[2] 为 null,即使其值已成功写入文本文件。

我已经在另一个项目中以相同的方式测试了拆分方法的实现,效果很好。在此之前,我也初始化了 num 变量,但无济于事。

有什么提示吗?感谢您的帮助!

MCVE的:

string[] readName = new String[3];
readName[0] = "Bob Ross";
var r = readName[1].Split("-"); // NRE here

完整代码

using System;
using static System.Console;
using System.IO;
using System.Runtime.InteropServices;

namespace Ch13Exercises
{

class Program
{
    static void Main()
    {
        string[] readName = new String[3];

        Write("Enter name: ");
        readName[0] = "Bob Ross";
        //readName[0] = ReadLine();
        WriteTo(readName);

        Write("Enter address: ");
        readName[1] = "123456, 2334 St";
        //readName[1] = ReadLine();
        WriteTo(readName);

        Write("Enter phone number in xxx-xxx-xxxx (dashes included): ");
        readName[2] = "452-564-7896";
        //readName[2] = ReadLine();
        WriteTo(readName);
    }

    public static void WriteTo(string[] readName) 
    {
        string path = @"A:\Q3.txt";
        if(File.Exists(path)) 
        {
            using(StreamWriter sw = new StreamWriter(path)) 
            {
                for(int i = 0; i < readName.Length; i++)
                {
                    if(i != 2)
                    {
                        sw.WriteLine(readName[i]);
                    }
                    else
                    {
                        string[] num = readName[i].Split('-'); //readName[i] null error here
                        sw.WriteLine(readName[i]); // writes phone number regardless of placement before or after

                    }


                }
                
            }
        }
    }
}
}
C# 数组 字符串 拆分 NullReferenceException

评论

1赞 Joel 7/30/2020
你是什么意思?writes phone number regardless of placement before or after
0赞 Alexei Levenkov 7/30/2020
看起来您在设置所有元素之前犯了一个复制粘贴错误......WriteTo(readName);
0赞 Alexei Levenkov 7/30/2020
我添加了最小的可重现示例,以显示您应该作为代码发布的内容。

答:

1赞 msmolcic 7/30/2020 #1

您调用方法 3 次。第一次调用它时,你只设置了数组的第一个元素,但你正在遍历所有元素,并尝试将它们的值写入文件中。数组的内容是 。因此,当您输入条件的一部分时,您正在尝试在 null 引用上调用方法。尝试删除所有方法调用,但最后一个方法调用除外,它将整个数组内容写入您的文件。WriteTo["Bob Ross", null, null]elseifreadName[i]nullSplitWriteTo

static void Main()
{
    string[] readName = new String[3];

    Write("Enter name: ");
    readName[0] = "Bob Ross";

    Write("Enter address: ");
    readName[1] = "123456, 2334 St";

    Write("Enter phone number in xxx-xxx-xxxx (dashes included): ");
    readName[2] = "452-564-7896";

    WriteTo(readName); // 'WriteTo' should be called only once here at the end
}