繁体   English   中英

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

[英]Why does a GetType on a string-property result in a NullReferenceException?

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

有人可以解释一下怎么来? 字符串支柱与int-prop的区别是什么?

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

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

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

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

propString的初始值为null。 我们不能执行null方法。 如果你初始化propString:propString =“”那么你可以执行没有Exception的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM