关于NullReferenceException的困惑

Dim*_*tri 2 c# arrays nullreferenceexception

据我所知Console.WriteLine()(或Console.Write())调用object的ToString()方法来获取对象的字符串represantation对吗?所以这两个电话Console.WriteLine()是一样的吗?

Foo foo = new Foo();

Console.WriteLine(foo); // This is same as the one bellow 
Console.WriteLine(foo.ToString());
Run Code Online (Sandbox Code Playgroud)

所以我们假设以下情况.我声明一个实例化一个Foos数组.

Foo[] foos = new Foo[10]; // After this line all 10 Foos are `null`s
Run Code Online (Sandbox Code Playgroud)

然后我在数组的任何元素上调用Console.WriteLine()而不实例化Foos本身.所以在这种情况下我们有一个Foos数组,并且数组中的每个Foo都是null如此调用Console.WriteLine()应该导致a NullReferenceException被抛出?但事情是,如果你这样称呼它

Console.WriteLine(foos[0])
Run Code Online (Sandbox Code Playgroud)

没有任何事情发生,除了Environment.NewLine在控制台窗口中写入,但如果你这样称呼它

Console.WriteLine(foos[0].ToString())
Run Code Online (Sandbox Code Playgroud)

它实际上抛出了一个NullReferenceException.这两个电话有什么区别?我的意思是在第一个我没有ToString()明确调用,但不应该由Console.WriteLine()隐式调用它?如何NullReferenceException在第一种情况下抛出?

Jon*_*eet 13

那么对Console.WriteLine()的这两个调用是一样的吗?

不.因为Console.WriteLine 调用ToString空引用 - 它只是使用空字符串.它检测到自己.

文件明确指出这一点:

如果value为null,则只写入行终止符.否则,调用值的ToString方法以生成其字符串表示形式,并将结果字符串写入标准输出流.

没有电话ToString,没有NullReferenceException.

string.Format表现方式相同.例如:

object value = null;
string text = string.Format("Value: '{0}'", value);
Run Code Online (Sandbox Code Playgroud)

将设置textValue: ''


Mar*_*zek 5

Console.WriteLine方法(对象)

如果值为null,则仅写入行终止符.否则,ToString调用value方法以生成其字符串表示形式,并将结果字符串写入标准输出流.

所以,Console.WriteLine(obj)Console.WriteLine(obj.ToString())不完全一样.

还有一点代码:

public virtual void WriteLine(object value)
{
    if (value == null)
    {
        this.WriteLine();
        return;
    }
    IFormattable formattable = value as IFormattable;
    if (formattable != null)
    {
        this.WriteLine(formattable.ToString(null, this.FormatProvider));
        return;
    }
    this.WriteLine(value.ToString());
}
Run Code Online (Sandbox Code Playgroud)