C#:动态地将基元转换为 Nullable<>
我使用反射来迭代对象的属性。对于 Nullable<>
类型,使用 PropertyType
属性正确返回类型。但是,当我调用属性 getter 时(通过 PropertyType.GetGetMethod().Invoke(obj, new object[0])
或 PropertyType.GetValue(obj, null)
,结果的类型是未包装的原语,而不是 Nullable<>
由于原因我不想深入,我需要将此结果转换为它的类型。 Nullable<>
类型在这种情况下会抛出 InvalidCastException
:
Convert.ChangeType(property.GetValue(obj, null), property.PropertyType);
是否有其他方法可以确保属性值的类型始终与属性的类型相同?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能在反射代码中执行此操作,因为在反射代码中您谈论的是
对象
,并且不存在盒装Nullable这样的东西 code> - 它可以是装箱的基础值,也可以是
null
。如果您知道实际类型,则可以使用构造函数创建包装值,但它必须只能分配给
Nullable
的类型化字段/变量- 不是object
- 否则 CLI 会再次解开它。然而,出于同样的原因,在使用反射时,您不需要将其包装起来;任何像
SetValue
这样的代码都会接受object
,并且会做正确的事情;无论它是null
还是装箱基础值,它都会被正确处理。基本上,CLI 在装箱和拆箱时会进行特殊处理
Nullable
,从而使问题无效。You cannot do that in reflection code, because in reflection code you are talking about
object
, and there is no such thing as a boxedNullable<T>
- it is either the boxed underlying value, or anull
.If you know the actual type, you can use the constructor to create a wrapped value, but it must only be assigned to a typed field/variable that is
Nullable<T>
- notobject
- else the CLI unwraps it again.However, for that same reason, you don't need it wrapped when using reflection; any code like
SetValue
will acceptobject
, and will do the right thing; regardless of whether it isnull
or a boxed underlying value, it will be handled correctly.Basically, the CLI has special handling when boxing and unboxing
Nullable<T>
that makes the question void.