本文介绍了可空性与可空的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对可空类型的以下行为大惑不解:

 类识别TestClass {
公众诠释?值= 0;
}

测试的TestClass =新识别TestClass();

现在, Nullable.GetUnderlyingType(test.value)返回底层可空类型,这是 INT
但是,如果我尝试获取字段类型像这样

 字段信息字段= typeof运算(识别TestClass).GetFields( BindingFlags.Instance | BindingFlags.Public)[0]; 

和我调用

  Nullable.GetUnderlyingType(field.FieldType)的ToString()

它返回 System.Nullable [System.Int32] 键入。因此,这意味着该方法 Nullable.GetUnderlyingType()有不同的效果,这取决于你如何获取成员类型。为什么会这样?如果我只是使用 test.value 我怎么能告诉它的可空不使用反射?


解决方案

可空类型都有点怪异。但是,至少他们的行为是有据可查的。



从C#编程指南MSDN上,
如何:确定可空类型at的:



It's worth pointing out that the distinction in your headline is inaccurate. The type behavior is not distinct based on local variables or properties, but on whether the type is accessed via a runtime object or by reflection (or use of the typeof operator). Your inference is understandable, since the types of local variables are usually only accessed by means of a runtime object, however, it is flawed, because if you access a nullable object at runtime via a property accessor then its behavior will be equivalent to that of a local variable.

Also, to answer the last part of your question explicitly: the only way to tell that test.value is nullable without using reflection would be to access it and get a NullReferenceException (which, of course, can only happen if test.value is null. As written, in your example, the value is not null, so determining this without reflection would be impossible

这篇关于可空性与可空的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 17:34