数组元素被认为是 null,即使它在使用 split 方法时显然不是?

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

我正在尝试仅使用数字来格式化 phone 数字,因此我使用了 Split 方法。但是,Visual Studio 表示 phone 数字存储变量 readName[2] 为空,即使它的值已成功写入文本文件。

我已经在另一个工作正常的项目中以同样的方式测试了 split 方法的实现。我也在此之前初始化了 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

                    }


                }
                
            }
        }
    }
}
}

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

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
}