小编Har*_*rsh的帖子

为什么“空整数”在字符串转换后不抛出“NullReferenceException”?

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

exception via using null int....System.NullReferenceException: Object reference not set to an instance of an object
Run Code Online (Sandbox Code Playgroud)

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

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

    try …
Run Code Online (Sandbox Code Playgroud)

c# nullreferenceexception

3
推荐指数
1
解决办法
740
查看次数

标签 统计

c# ×1

nullreferenceexception ×1