带有委托的反射



我使用反射来比较两个对象列表(相同类型)并收集具有不同值的属性列表。我可能遍历大量对象列表比较中表现滞后。我开始了解在反射中使用委托,这样我们就可以绕过耗时的.GetValue(obj, null)。我的类属性的类型很广。它可以是string、int和enum。现有的解决办法对我不起作用。谢谢你的帮助。

我用来比较相同类型

的两个对象的代码
public List<string> Compare<T>(object A, object B)
{
var type = typeof(T);
var allProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
List<string> unequalProperties =
(
from pi in allProperties 
let AValue = type.GetProperty(pi.Name).GetValue(A, null)
let BValue = type.GetProperty(pi.Name).GetValue(B, null)
where AValue != BValue && (AValue == null || !AValue.Equals(BValue))
select pi.Name
).ToList();
return unequalProperties;
}

两个.GetValue(A/B, null)正在产生延迟,我想使用委托跳过。

通过将代码放入泛型类中,可以将getter委托缓存在静态字段中。

你可以使用一个两级的类层次结构,使用更多的泛型来缓存属性本身。

public List<string> Compare<T>(T A, T B)
{
return GenericComparer<T>.Compare(A, B);
}
abstract class PropertyCompareBase<T>
{
public string Name;
public abstract bool CompareProperty(T A, T B);
}
class PropertyCompare<T, TProperty> : PropertyCompareBase<T>
{
Func<T, TProperty> Getter;
public PropertyCompare(PropertyInfo prop)
{
Name = prop.Name;
Getter = (Func<T, TProperty>)prop.GetMethod.CreateDelegate(typeof(Func<T, TProperty>));
}
public override bool CompareProperty(T A, T B)
{
return EqualityComparer<TProperty>.Default.Equals(Getter(A), Getter(B));
}
}
static class GenericComparer<T>
{
static List<PropertyCompareBase<T>> properties = typeof(T)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.GetIndexParameters().Length == 0)
.Select(p => (PropertyCompareBase<T>)Activator.CreateInstance(
typeof(PropertyCompare<,>)
.MakeGenericType(typeof(T), p.PropertyType),
p))
.ToList();
static public List<string> Compare(T A, T B)
{
List<string> unequalProperties =
properties.Where(p => !p.CompareProperty(A, B))
.Select(p => p.Name)
.ToList();
return unequalProperties;
}
}

dotnetfiddle

最新更新