2
public static bool PropertiesEqual<T>(this T self, T other, string[] skip)
{
    if (self.Equals(other)) return true;

        var primitive = (from p in typeof(T).GetProperties() 
                         where !skip.Contains(p.Name) 
                         && p.PropertyType.IsSimpleType() 
                         select p).ToList();

        var rest = (from p in typeof(T).GetProperties()
                      where !p.PropertyType.IsSimpleType() select p).ToList();

        foreach(var pi in rest)
        {
            var selfValue = pi.GetValue(self, null);
            var otherValue = pi.GetValue(other, null);

            //var result = selfValue.PropertiesEqual(otherValue);

            if (!object.Equals(selfValue, otherValue))
                return false;
        }


        foreach (var pi in primitive)
        {
            var selfValue = pi.GetValue(self, null);
            var otherValue = pi.GetValue(other, null);

            return object.Equals(selfValue, otherValue);
        }

        return true;
}

public static bool IsSimpleType(this Type type)
{
    return (type.IsValueType || type.IsPrimitive || 
       type == typeof(String) || Convert.GetTypeCode(type) != TypeCode.Object);
}

このメソッドを使用して、エンティティ インスタンスの等価性を比較しています。最初のレベルではうまく機能しますが、rest(アタッチされたエンティティ) を反復処理して、このメソッド (コメント行) を再帰的に呼び出したいと思います。

問題は、再帰呼び出しで入力されるため、結果がゼロになることですself。最初のレベルでタイプを検査すると、実際のタイプが得られますが、2 番目のレベルでは. を使用してみましたが、役に立ちませんでした。otherobjectprimitiveselfthisobjectConvert.ChangeType

4

3 に答える 3

1

self と other の値の割り当てをこれに変更するとどうなりますか?

var selfValue = Convert.ChangeType(pi.GetValue(self, null), pi.PropertyType);
var otherValue = Convert.ChangeType(pi.GetValue(other, null), pi.PropertyType);

T はオブジェクトになりますが、self と other は正しい型であることに気付きました。したがって、typeof(T) からプロパティを取得する代わりに、次のようにしてください。

var rest = (from p in self.GetType().GetProperties() select p).ToList();

私の簡単なテストでは、それは機能し、必要な小道具を返しました。この1行以上を変更する必要があるかもしれません:)

于 2013-11-13T09:17:43.287 に答える