3

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

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

“对象与目标类型不匹配”

...错误在

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;
}
4

3 回答 3

3

在 .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;

    ...

当然这并没有考虑到一些定义在 on 上的属性T可能不存在于 上T2,反之亦然。

于 2013-06-18T19:56:28.917 回答
0

因为manuallyCreated不是类型T2。尝试在该类型上获取具有相同名称的属性对象,它应该可以工作(或者如果您假设 T2 中的所有属性也在 T1 中,您会得到一个更好的错误):

public static bool SameCompare<T, T2>(T manuallyCreated, T2 generated){
    var propertiesForGenerated = typeof(T2).GetProperties();
    int compareValue = 0;

    foreach (var prop in propertiesForGenerated) {
        var firstProperty = typeof(T).GetProperty(prop.Name);
        var valFirst = firstProperty.GetValue(manuallyCreated, null) as IComparable;
        var valSecond = prop.GetValue(generated, null) as IComparable;
        ...
    }
}
于 2013-06-18T19:56:22.093 回答
0

我相信最好有你需要比较的属性的接口,然后我会继承IEqualityComparer<YourInterface>

在 Equals 和 GetHashCode 中

public bool Equals(YourInterface one, YourInterface two)
{
    return this.GetHashCode(one) == this.GetHashCode(two);
}

public int GetHashCode(YourInterface  test)
{
    if(test == null)
    {

      return 0;
    }

     int hash = 0;
     //// get hash or set int on each property.

     return hash;
 }
于 2013-06-18T20:09:40.827 回答