【发布时间】:2019-05-01 14:52:15
【问题描述】:
我正在尝试使用反射来比较相同类型对象的属性。
问题是引用类型 <T> == <T> 不会这样做所以我尝试使用反射来比较 IEnumerable 的值,为此我尝试调用 Enumerable.Except(T)
它适用于List,但不适用于Dictionaries:
无法转换类型的对象 'd__57
1[System.Collections.Generic.KeyValuePair2[System.String,System.String]]' 输入“System.Collections.Generic.IEnumerable`1[System.Object]”。
问题在于这段代码:
var typeKeyValuePair = typeof(KeyValuePair<,>);
Type[] typeArgs = { args[0], args[1] };
exceptMethods = typeof(Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.FirstOrDefault(mi => mi.Name == "Except")
?.MakeGenericMethod(typeKeyValuePair.MakeGenericType(typeArgs));
信息的完整代码
public static List<Variance> DetailedCompare<T>(this T val1, T val2)
{
List<Variance> variances = new List<Variance>();
PropertyInfo[] propertyInfo = val1.GetType().GetProperties();
foreach (PropertyInfo p in propertyInfo)
{
Variance v = new Variance();
v.Prop = p.Name;
v.valA = p.GetValue(val1);
v.valB = p.GetValue(val2);
switch (v.valA)
{
case null when v.valB == null:
continue;
case null:
variances.Add(v);
continue;
}
if (v.valA.Equals(v.valB)) continue;
if (typeof(IEnumerable).IsAssignableFrom(p.PropertyType))
{
//string
if (p.PropertyType == typeof(string))
{
variances.Add(v);
continue;
}
var args = p.PropertyType.GetGenericArguments();
MethodInfo exceptMethods = null;
if (args.Length == 2) //dictionaries
{
variances.Add(v); // add to difference while not able to compare
/*
var typeKeyValuePair = typeof(KeyValuePair<,>);
Type[] typeArgs = { args[0], args[1] };
exceptMethods = typeof(Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.FirstOrDefault(mi => mi.Name == "Except")
?.MakeGenericMethod(typeKeyValuePair.MakeGenericType(typeArgs));*/
}
else if (args.Length == 1)//lists
{
exceptMethods = typeof(Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.FirstOrDefault(mi => mi.Name == "Except")
?.MakeGenericMethod(p.PropertyType.GetGenericArguments().FirstOrDefault());
}
else//not
{
variances.Add(v);
}
if (exceptMethods != null)
{
try
{
var res1 = (IEnumerable<object>)exceptMethods.Invoke(v.valA, new[] { v.valA, v.valB });
var res2 = (IEnumerable<object>)exceptMethods.Invoke(v.valB, new[] { v.valB, v.valA });
if (res1.Any() != res2.Any()) variances.Add(v);
}
catch (Exception ex)
{
}
/* if (v.valA.Except(v.valB).Any() || v.valB.Except(v.valA).Any())
{
variances.Add(v);
}*/
}
}
}
return variances;
}
}
class Variance
{
public string Prop { get; set; }
public object valA { get; set; }
public object valB { get; set; }
}
【问题讨论】:
-
值得尝试重新考虑这一点。你能不能让
T类型实现某种接口,或者甚至只是覆盖它们上的Object.Equals。 -
我尝试了代码,但看起来它也不适用于类型列表,例如
List<int>类型。您能否将您的示例扩展为对DetailedCompare的简短函数调用?
标签: c# .net .net-core system.reflection