为什么字符串属性上的GetType会导致NullReferenceException?

时间:2009-10-09 13:40:39

标签: c# properties nullreferenceexception gettype

当我在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 (?!)

有人可以解释为什么会这样?字符串-prop与int-prop有什么不同?

4 个答案:

答案 0 :(得分:8)

如果属性的值为null,那么在尝试访问对象方法或属性(例如GetType())时,您将获得NullReferenceException。像intDateTime这样的原始类型是值类型,因此不能保存null值,这就是GetType()不会失败的原因成员职能。

答案 1 :(得分:2)

因为string是引用类型,而其他不是。默认情况下,DateTime和Int必须具有值,它们不能为空。

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

答案 2 :(得分:2)

要强调其他答案所表示的内容,请将int更改为int?和DateTime到DateTime?并尝试再次运行代码。由于这些值现在可以保存空值,因此您将获得相同的异常。

答案 3 :(得分:1)

propString的初始值为null。我们不能执行null方法。如果你初步启动propString:propString =“”那么你可以执行GetType()而不用Exception

代码无例外:

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
相关问题