[英]Why does a GetType on a string-property result in a NullReferenceException?
When I call a GetType on a int- or a DateTime-property, I get the expected results, but on a string-property, I get 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 (?!)
Can someone explain how come ? 有人可以解释一下怎么来? In what way differs a string-prop from a int-prop ?
字符串支柱与int-prop的区别是什么?
If the property's value is null
, then you'll get a NullReferenceException when trying to access object methods or properties, like GetType()
. 如果属性的值为
null
,那么在尝试访问对象方法或属性(如GetType()
时,您将获得NullReferenceException。 Primitive types like int
and DateTime
are value types, and as such cannot hold a null
value, which is why GetType()
won't fail any more than any of their other member functions. 像
int
和DateTime
这样的原始类型是值类型,因此不能保存null
值,这就是GetType()
不会失败的原因,而不是任何其他成员函数。
Because string is a reference type where the others are not. 因为string是引用类型,而其他不是。 The DateTime and the Int have to have values by default, they can't be null.
默认情况下,DateTime和Int必须具有值,它们不能为空。
What you have to understand is the the compiler is creating a variable for you to store the information. 你必须要了解的是编译器正在为你创建一个存储信息的变量。 In C# 3.0 you don't have to explicitly declare it, but it is still there, so it's creating a DateTime variable and an int variable and initializing them to their default values so not to cause a compiler error.
在C#3.0中,您不必显式声明它,但它仍然存在,因此它创建一个DateTime变量和一个int变量并将它们初始化为默认值,以免引起编译器错误。 With a string, it doesn't need to do this (initialize a default value), because it's a reference type.
使用字符串,它不需要执行此操作(初始化默认值),因为它是引用类型。
To emphasize what the other answers have indicated, change int to int? 要强调其他答案所指示的内容,请将int更改为int? and DateTime to DateTime?
和DateTime到DateTime? and try running the code again.
并尝试再次运行代码。 Since those values can now hold nulls, you will get the same exception.
由于这些值现在可以保存空值,因此您将获得相同的异常。
Initial value of propString is null. propString的初始值为null。 We cann't execute method of null.
我们不能执行null方法。 If you initialaze propString: propString = "" then you can execute GetType() without Exception
如果你初始化propString:propString =“”那么你可以执行没有Exception的GetType()
Code without 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.