C#:动态地将基元转换为 Nullable<>

发布于 2024-12-20 20:58:00 字数 519 浏览 1 评论 0 原文

我使用反射来迭代对象的属性。对于 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);

是否有其他方法可以确保属性值的类型始终与属性的类型相同?

I'm using reflection to iterate through the properties of objects. For Nullable<> types, the type is being returned correctly using the PropertyType property. However, when I invoke the property getter (either via PropertyType.GetGetMethod().Invoke(obj, new object[0]) or PropertyType.GetValue(obj, null), the result's type is the unwrapped primitive, not Nullable<>. For reason's I'd rather not go into, I need to convert this result into its Nullable<> type. This throws an InvalidCastException in such cases:

Convert.ChangeType(property.GetValue(obj, null), property.PropertyType);

Is there another way to ensure the property value's type is always the same as the property's type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦萦几度 2024-12-27 20:58:00

您不能在反射代码中执行此操作,因为在反射代码中您谈论的是对象,并且不存在盒装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 boxed Nullable<T> - it is either the boxed underlying value, or a null.

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> - not object - 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 accept object, and will do the right thing; regardless of whether it is null 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文