映射对象属性,不包括类型



我目前使用的

public static void MapObjectPropertyValues(object e1, object e2)
    {
        foreach (var p in e1.GetType().GetProperties())
        {
            if (e2.GetType().GetProperty(p.Name) != null)
            {
                p.SetValue(e1, e2.GetType().GetProperty(p.Name).GetValue(e2, null), null);
            }   
        }
    }

我想传递第三个参数,一个我想从映射中排除的类型的通用列表。例如字符串和布尔值。并检查p是否属于列表中的类型。感谢您的帮助!

如果类型完全匹配,则可以使用p.PropertyType属性来排除赋值。

public static void MapObjectPropertyValues(object e1,
                  object e2,
                  IEnumerable<Type> excludedTypes)
{
    foreach (var p in e1.GetType().GetProperties())
    {
        if (e2.GetType().GetProperty(p.Name) != null && 
        // next line added
        !(excludedTypes.Contains(p.PropertyType)))
        {
            p.SetValue(e1, e2.GetType().GetProperty(p.Name).GetValue(e2, null), null);
        }
     }
}

最新更新