C#-GetValue-对象与目标类型不匹配

我正在尝试编写一种比较两个对象的通用方法(我故意要引入两种不同的类型.第二种具有与第一种相同的属性.第一种具有更多的属性.)

我想确保这些属性具有相同的值.以下代码适用于我在对象中拥有的大多数属性,但有时会抛出:

“Object Does Not Match Target Type”

…错误

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;
}
最佳答案
.NET中在类型上定义的每个属性都不同,即使它们具有相同的名称.您必须这样做:

foreach (var prop in propertiesForGenerated) 
{
    var otherProp = typeof(T).GetProperty(prop.Name);
    var valFirst = otherProp.GetValue(manuallyCreated, null) as IComparable;
    var valSecond = prop.GetValue(generated, null) as IComparable;

    ...

当然,这没有考虑到T上定义的某些属性可能在T2上不存在,反之亦然.

点击查看更多相关文章

转载注明原文:C#-GetValue-对象与目标类型不匹配 - 乐贴网