【问题标题】:Why does a GetType on a string-property result in a NullReferenceException?为什么字符串属性上的 GetType 会导致 NullReferenceException?
【发布时间】:2010-12-05 08:32:26
【问题描述】:

当我在 int 或 DateTime 属性上调用 GetType 时, 我得到了预期的结果,但是在字符串属性上, 我得到一个 NullReferenceException (?):

private int      PropInt    { get; set; }
private DateTime PropDate   { get; set; }
private string   propString { get; set; }

WriteLine(PropInt.GetType().ToString());    // Result : System.Int32
WriteLine(PropDate.GetType().ToString());   // Result : System.DateTime
WriteLine(propString.GetType().ToString()); // Result : NullReferenceException (?!)

有人能解释一下是怎么回事吗? string-prop 和 int-prop 有什么不同?

【问题讨论】:

    标签: c# properties nullreferenceexception gettype


    【解决方案1】:

    如果属性的值为null,那么在尝试访问对象方法或属性时,您将收到 NullReferenceException,例如GetType()。像 intDateTime 这样的原始类型是值类型,因此不能保存 null 值,这就是为什么 GetType() 不会比它们的任何其他成员函数更失败的原因。

    【讨论】:

      【解决方案2】:

      为了强调其他答案所表明的内容,请将 int 更改为 int?和日期时间到日期时间?并尝试再次运行代码。由于这些值现在可以包含空值,因此您将得到相同的异常。

      【讨论】:

      • 其实这是不正确的。虽然您可以将Nullable<T> 分配给null 并将其与null 进行比较,但该值实际上并不是nullNullable<T>struct 并且必须遵循所有值类型约定,例如不能存储 null。赋值和比较只是无参数构造函数和检查HasValue 属性的语法糖。
      • 否; Bomlin 是正确的;未初始化的Nullable<T>GetType() 上引发异常;在这里查看原因:stackoverflow.com/questions/194484/…
      【解决方案3】:

      因为字符串是一种引用类型,而其他类型则不是。 DateTime 和 Int 默认必须有值,不能为空。

      您必须了解的是编译器正在为您创建一个变量来存储信息。在 C# 3.0 中,您不必显式声明它,但它仍然存在,因此它创建了一个 DateTime 变量和一个 int 变量并将它们初始化为默认值,以免导致编译器错误。对于字符串,它不需要这样做(初始化一个默认值),因为它是一个引用类型。

      【讨论】:

      • -1...全局变量? .NET 中没有这样的概念,它的目的是什么?
      【解决方案4】:

      propString 的初始值为空。我们不能执行 null 的方法。如果你初始化 propString: propString = "" 那么你可以执行 GetType() 没有异常

      代码无一例外:

      private int      PropInt    { get; set; }
      private DateTime PropDate   { get; set; }
      private string   propString { get; set; }
      
      propString = ""; // propString != null
      
      WriteLine(PropInt.GetType().ToString());    // Result : System.Int32
      WriteLine(PropDate.GetType().ToString());   // Result : System.DateTime
      WriteLine(propString.GetType().ToString()); // Result : System.String
      

      【讨论】:

        猜你喜欢
        • 2012-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-22
        相关资源
        最近更新 更多