c# - 将属性表单对象复制到另一个对象的扩展方法,第一次尝试

标签 c# .net reflection extension-methods

我正在尝试编写一个扩展方法,我可以使用它来将值从一个对象属性复制到另一个不同类型的对象,只要属性名称和类型完全匹配即可。

这是我的:

public static T CopyFrom<T>(this T toObject, object fromObject)
    {
        var fromObjectType = fromObject.GetType();
        var fromProperties = fromObjectType.GetProperties();

        foreach (PropertyInfo toProperty in toObject.GetType().GetProperties())
        {
            PropertyInfo fromProperty = fromObjectType.GetProperty(toProperty.Name);

            if (fromProperty != null) // match found
            {
                // check types
                var fromType = fromProperty.PropertyType.UnderlyingSystemType;
                var toType = toProperty.PropertyType.UnderlyingSystemType;

                if (toType.IsAssignableFrom(fromType))
                {
                    toProperty.SetValue(toObject, fromProperty.GetValue(fromObject, null), null);
                }
            }
        }

        return toObject;
    }

这对于非盒装类型非常有用,但是 Nullable<T>调用时返回 false

toType.IsAssignableFrom(fromType)

因为它的类型是Nullable<T>并且不是基础类型 T .

我读了hereGetType()应该拆箱 Nullable<T>所以它返回 T但如果我在 PropertyInfo.PropertyType 上调用它我得到 ReflectedMemberInfo而不是 T 类型我在找。

我想我在这里遗漏了一些明显的东西,所以我想我会把它开放给 SO 以获得一些建议。

有人有什么想法吗?

更新:这是任何搜索此内容的人的 final方法。

 public static T CopyFrom<T>(this T toObject, object fromObject)
    {
        var fromObjectType = fromObject.GetType();

        foreach (PropertyInfo toProperty in toObject.GetType().GetProperties())
        {
            PropertyInfo fromProperty = fromObjectType.GetProperty(toProperty.Name);

            if (fromProperty != null) // match found
            {
                // check types
                var fromType = Nullable.GetUnderlyingType(fromProperty.PropertyType) ?? fromProperty.PropertyType;
                var toType = Nullable.GetUnderlyingType(toProperty.PropertyType) ?? toProperty.PropertyType;

                if (toType.IsAssignableFrom(fromType))
                {
                    toProperty.SetValue(toObject, fromProperty.GetValue(fromObject, null), null);
                }
            }
        }

        return toObject;
    }

最佳答案

您正在寻找 Nullable.GetUnderlyingType .

例如:

toType = Nullable.GetUnderlyingType(toType) ?? toType;

关于c# - 将属性表单对象复制到另一个对象的扩展方法,第一次尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2826748/

相关文章:

c# - 激活器.CreateInstance : Could not load type from assembly

reflection - Go: reflect : 调用输入参数太少

c# - while 循环中的高 CPU 使用率,正在检查按键事件

c# - 如何用私钥加密字符串并用公钥解密?

c# - 使用反射是一种设计味道吗?

c# - 对 .cs 文件运行强化扫描

java - 在 Java 中使用反射创建一个新实例,并将引用变量类型设置为新实例类名?

c# - 在 .net 中创建不可变类型时,拥有公共(public)字段是否有效?

c# - 自动调用基方法

.net - SandCaSTLe 帮助文件生成器 : Search not working