【发布时间】:2015-05-06 14:18:33
【问题描述】:
我正在尝试编写一个通用方法来比较两个对象(我故意输入了两种不同的类型。第二个具有与第一个相同的属性。第一个只是更多。)。
我想确保属性具有相同的值。以下代码适用于我在对象中拥有的大多数属性,但偶尔会抛出:
“对象与目标类型不匹配”
...错误
var valFirst = prop.GetValue(manuallyCreated, null) as IComparable;
public static bool SameCompare<T, T2>(T manuallyCreated, T2 generated){
var propertiesForGenerated = generated.GetType().GetProperties();
int compareValue = 0;
foreach (var prop in propertiesForGenerated) {
var valFirst = prop.GetValue(manuallyCreated, null) as IComparable;
var valSecond = prop.GetValue(generated, null) as IComparable;
if (valFirst == null && valSecond == null)
continue;
else if (valFirst == null) {
System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
return false;
}
else if (valSecond == null) {
System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
return false;
}
else if (prop.PropertyType == typeof(System.DateTime)) {
TimeSpan timeDiff = (DateTime)valFirst - (DateTime)valSecond;
if (timeDiff.Seconds != 0) {
System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
return false;
}
}
else
compareValue = valFirst.CompareTo(valSecond);
if (compareValue != 0) {
System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
return false;
}
}
System.Diagnostics.Debug.WriteLine("All values are equal");
return true;
}
【问题讨论】:
-
抛出时是什么情况?
-
当我检查一个名为 Procedure.类型为long,值为845
-
只有当 T2 相等或从 T 继承时,此代码才能完全无故障地工作。您不检查的约束,如果不是这种情况,它将因此异常而爆炸。显然,这个问题需要一个简单的重现示例来使其清晰。由于这使用了反射,因此避免将 generated 声明为类型 T 是没有意义的,因此编译器会在您出错时告诉您。
标签: c# generics reflection