Pergunta

Quero comparar dois objetos de versões diferentes e exibir suas diferenças na interface do usuário.

Primeiro, chamo um método para saber se há alguma diferença entre os dois objetos

O método é:

public bool AreEqual(object object1,object object2, Type comparisionType)

Se o método acima retornar verdadeiro, eu chamo o GetDifferences Método para obter as diferenças que são:

public ObjectDifference[] GetObjectDifferences(object object1, object object2, Type comparisionType)
{
  ArrayList memberList = new ArrayList();
  ArrayList differences = new ArrayList();

  memberList.AddRange(comparisionType.GetProperties());
  memberList.AddRange(comparisionType.GetFields());

  for (int loopCount = 0; loopCount < memberList.Count; loopCount++)
  {
    object objVal1 = null;
    object objVal2 = null;
    MemberInfo member = ((MemberInfo)memberList[loopCount]);
    switch (((MemberInfo)memberList[loopCount]).MemberType)
    {
      case MemberTypes.Field:
        objVal1 = object1 != null ? ((FieldInfo)memberList[loopCount]).GetValue(object1) : null;
        objVal2 = object2 != null ? ((FieldInfo)memberList[loopCount]).GetValue(object2) : null;
        break;
      case MemberTypes.Property:

        objVal1 = object1 != null ? ((PropertyInfo)memberList[loopCount]).GetValue(object1, null) : null;
        objVal2 = object2 != null ? ((PropertyInfo)memberList[loopCount]).GetValue(object2, null) : null;
        break;
      default:
        break;
    }

    if (AreValuesDifferentForNull(objVal1, objVal2))
    {
      ObjectDifference obj = new ObjectDifference(objVal1, objVal2, member, member.Name);
      differences.Add(obj);
    }
    else if (AreValuesDifferentForPrimitives(objVal1, objVal2))
    {
      ObjectDifference obj = new ObjectDifference(objVal1, objVal2, member, member.Name);
      differences.Add(obj);
    }
    else if (AreValuesDifferentForList(objVal1, objVal2))
    {
      ObjectDifference[] listDifference = GetListDifferences((ICollection)objVal1, (ICollection)objVal2, member);
      differences.AddRange(listDifference);
    }
    else if ((!AreValuesEqual(objVal1, objVal2)) && (objVal1 != null || objVal2 != null))
    {
      ObjectDifference obj = new ObjectDifference(objVal1, objVal2, member, member.Name);
      differences.Add(obj);
    }
  }
  return (ObjectDifference[])differences.ToArray(typeof(ObjectDifference));
}


public class ObjectDifference
{
  private readonly object objectValue1;
  private readonly object objectValue2;
  private readonly System.Reflection.MemberInfo member;
  private readonly string description;

  public object ObjectValue1
  {
    get { return objectValue1; }
  }
  public object ObjectValue2
  {
    get { return objectValue2; }
  }
  public System.Reflection.MemberInfo Member
  {
    get { return member; }
  }
  public string Description
  {
    get { return description; }
  }

  public ObjectDifference(object objVal1, object objVal2, System.Reflection.MemberInfo member, string description)
  {
    this.objectValue1 = objVal1;
    this.objectValue2 = objVal2;
    this.member = member;
    this.description = description;
  }
}

Para cada diferença, crio um objeto do tipo ObjectDifference e a adiciono à matriz. A parte destacada é aquela em que estou preso! Se o objeto contiver outro objeto complexo, meu programa me dá as diferenças, mas eu não sei a que tipo pertencia

Por exemplo, eu tenho dois objetos do nome do tipo

class Name
{
  string firstName, LastName;
  List phNumber;
}

class PhoneNumber
{
  string officeNo, MobileNo, HomeNo;
}

Ao comparar dois objetos, a saída que recebo é clara -

  • firstname - John Mary
  • LastName - Cooper Lor
  • officeNo - 22222 44444
  • MobileNo - 989898 089089
  • HomeNo - 4242 43535

A hierarquia que officeNo é do tipo PhoneNumber está perdido, o que é importante para eu exibir.

Como devo manter esse tipo de árvore enquanto cria diferenças? Espero poder fazer com que meu problema seja entendido.

Foi útil?

Solução

O que você está tentando fazer e exibir é inerentemente complexo. Eu fiz isso no passado (para processos baseados em diffgram/delta) e até mesmo tentando exibição mudanças aninhadas em um simples e amigável O caminho é complicado.

Se se encaixar na sua base de usuário, uma opção pode ser simplesmente serializar os dois gráficos como XML e usar algo como xml diff.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top