Nie szukam dla porównania dwóch strukturach, które zwraca bool, zastanawiam się, czy istnieje sposób uzyskać, które pola dwóch kodowanym (taką samą strukturę, ale może różne wartości) są różne. Zasadniczo chcę prostszy sposób wykonać następujące czynności:Porównanie wartości dwóch kodowanym w C#
public class Diff
{
public String VarName;
public object Val1;
public object Val2;
public Diff(String varName, object val1, object val2)
{
VarName = varName;
Val1 = val1;
Val2 = val2;
}
public override string ToString()
{
return VarName + " differs with values " + Val1 + " and " + Val2;
}
}
public struct TestStruct
{
public int ValueOne;
public int ValueTwo;
public int ValueThree;
public List Compare(TestStruct inTestStruct)
{
List diffs = new List();
if (ValueOne != inTestStruct.ValueOne)
{
diffs.Add(new Diff("ValueOne", ValueOne, inTestStruct.ValueOne));
}
if (ValueTwo != inTestStruct.ValueTwo)
{
diffs.Add(new Diff("ValueTwo", ValueTwo, inTestStruct.ValueTwo));
}
if (ValueThree != inTestStruct.ValueThree)
{
diffs.Add(new Diff("ValueThree", ValueThree, inTestStruct.ValueThree));
}
return diffs;
}
}
public CompareStructsExample()
{
TestStruct t1 = new TestStruct();
t1.ValueOne = 1;
t1.ValueTwo = 8;
t1.ValueThree = 5;
TestStruct t2 = new TestStruct();
t2.ValueOne = 3;
t2.ValueTwo = 8;
t2.ValueThree = 7;
List diffs = t1.Compare(t2);
foreach (Diff d in diffs)
{
System.Console.WriteLine(d.ToString());
}
}
Zastanawiam się, czy istnieje sposób, aby to zrobić z serializacji jakiejś, lub jeśli jest to jedyny sposób, aby zorientować się, które wartości zostały zmienione . Nawet jeśli istnieje lepszy sposób implementacji funkcji Compare, również bym to zrobił.
Sprawdź moje rozwiązanie linq. Jest naprawdę mały. – johnnycrash