2

当我在 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 有何不同?

4

4 回答 4

8

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

于 2009-10-09T13:42:13.243 回答
2

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

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

于 2009-10-09T13:42:18.313 回答
2

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

于 2009-10-09T13:48:57.817 回答
1

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
于 2009-10-09T13:47:16.450 回答