【发布时间】:2023-03-11 11:08:02
【问题描述】:
对于SO question,我最近编写了一个通用扩展方法,它应该从另一个对象加载对象,即将源的所有属性分配给目标,如果属性是引用类型,则递归执行此操作。我使用反射已经走了很远,但是当涉及到引用类型的属性类型时遇到了问题,这是我的第一种方法:
第一种方法:
public static void Load<T>(this T target, T source, bool deep)
{
foreach (PropertyInfo property in typeof(T).GetProperties())
{
if (property.CanWrite && property.CanRead)
{
if (!deep || property.PropertyType.IsPrimitive || property.PropertyType == typeof(String))
{
property.SetValue(target, property.GetValue(source, null), null);
}
else
{
property.GetValue(target, null).Load(property.GetValue(source, null), deep);
}
}
}
}
这里的问题是PropertyInfo.GetValue 返回一个对象,随后T 在递归调用中将等于object,我无法再获得该对象实际具有的属性。
我构想了一种解决方法,它要求您显式传递类型,这是非常多余的,因为理论上它应该可以在没有以下情况下进行管理:
public static void Load<T>(this T target, Type type, T source, bool deep)
{
foreach (PropertyInfo property in type.GetProperties())
{
if (property.CanWrite && property.CanRead)
{
if (!deep || property.PropertyType.IsPrimitive || property.PropertyType == typeof(String))
{
property.SetValue(target, property.GetValue(source, null), null);
}
else
{
object targetPropertyReference = property.GetValue(target, null);
targetPropertyReference.Load(targetPropertyReference.GetType(), property.GetValue(source, null), deep);
}
}
}
}
我也尝试过使用dynamic targetPropertyReference,但是我得到了一个运行时异常,无法找到Load 方法,这太令人生气了。
除此之外,Convert.ChangeType 也很容易返回血腥的object,我似乎无法将对象投射到它的本来面目。当然我已经在网上寻找过这个问题的答案,但到目前为止我一直没有成功。
【问题讨论】:
标签: c# generics reflection types extension-methods