使用反射将 Nullable 属性复制到非 Nullable 版本

编程入门 行业动态 更新时间:2024-10-23 21:41:00
本文介绍了使用反射将 Nullable 属性复制到非 Nullable 版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写代码以使用反射将一个对象转换为另一个对象...

I am writing code to transform one object to another using reflection...

它正在进行中,但我认为可以归结为以下情况,我们相信这两个属性具有相同的类型:

It's in progress but I think it would boil down to the following where we trust both properties have the same type:

private void CopyPropertyValue(object source, string sourcePropertyName, object target, string targetPropertyName) { PropertyInfo sourceProperty = source.GetType().GetProperty(sourcePropertyName); PropertyInfo targetProperty = target.GetType().GetProperty(targetPropertyName); targetProperty.SetValue(target, sourceProperty.GetValue(source)); }

但是我有一个额外的问题,即源类型可能是 Nullable 而目标类型不是.例如 Nullable => int.在这种情况下,我需要确保它仍然有效并且执行了一些合理的行为,例如NOP 或为该类型设置默认值.

However I have the additional issue that the source type might be Nullable and the target type not. e.g Nullable<int> => int. In this case I need to make sure it still works and some sensible behaviour is performed e.g. NOP or set the default value for that type.

这会是什么样子?

推荐答案

鉴于 GetValue 返回一个 boxed 表示,这将是一个空值引用可以为 null 的类型,很容易检测到,然后根据需要进行处理:

Given that GetValue returns a boxed representation, which will be a null reference for a null value of the nullable type, it's easy to detect and then handle however you want:

private void CopyPropertyValue( object source, string sourcePropertyName, object target, string targetPropertyName) { PropertyInfo sourceProperty = source.GetType().GetProperty(sourcePropertyName); PropertyInfo targetProperty = target.GetType().GetProperty(targetPropertyName); object value = sourceProperty.GetValue(source); if (value == null && targetProperty.PropertyType.IsValueType && Nullable.GetUnderlyingType(targetProperty.PropertyType) == null) { // Okay, trying to copy a null value into a non-nullable type. // Do whatever you want here } else { targetProperty.SetValue(target, value); } }

更多推荐

使用反射将 Nullable 属性复制到非 Nullable 版本

本文发布于:2023-11-11 06:59:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577701.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   属性   版本   Nullable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!