为什么 'null integer' 在字符串转换后不抛出 'NullReferenceException'?

Why is 'null integer' not throwing 'NullReferenceException' after string conversion?

在下面的代码中,我得到了空引用异常,这很好,因为字符串为空 -

using System;

public class Test
{
  static string  r = null;
  public static void Main()
  {
    string s = "";

    try
    {
        s = r.ToString(); 
        Console.Write("Successful");
    }
    catch(Exception ex)
    {
        Console.WriteLine("exception via using null int...." + ex);
    }

    Console.WriteLine(s);
  }
}

输出:

exception via using null int....System.NullReferenceException: Object reference not set to an instance of an object

但是当我使用这段代码时,为什么我没有得到空引用异常? 可空整数变量是否没有空值?

using System;
public class Test
{
  public static void Main()
  {
    string s = "";
    int? i = null;

    try
    {
        s = i.ToString(); 
        Console.Write("Successful");
    }
    catch(Exception ex)
    {
        Console.WriteLine("exception via using null int...." + ex);
    }


    Console.WriteLine(s);
  }
}

输出:

Successful

因为 S 是内存中的一个对象,它包含一个零字符的字符串,但是 r 只是调用计算机来保留一个位置但是你没有说它是不是字符串所以 toString 是不可能的

当用一个值声明 S 时,编译器确保它是一个字符串对象,并且它从对象 String 获取所有字符串方法。

如果给它赋值,打印时s是否包含实际值? int? 的值应该通过

访问
.Value

所以

int?.ToString() 

应该打印它的类型,而不是它的值,所以 null 在这里很好,另请参阅:C# Nullable Types and the Value property

T? 表示法是 System.Nullable<T> 的简写。这个类型是结构体,不是引用类型,不能是null。它有一个接受 null 引用的构造函数,它所做的是在其中创建包含 null 的结构。

int?是值类型,不是引用类型。 NullReferenceException 仅针对引用类型抛出。