我想比较同一个类的两个不同对象,并将该值存储在另一个类的列表中。
它适用于基本数据类型,但是当类包含列表的属性或另一个类的属性时,我遇到了问题。
class Program
{
static void Main()
{
SomeCustomClass a = new SomeCustomClass();
SomeCustomClass b = new SomeCustomClass();
a.CwNumber = "A";
a.MaterialId = 1;
a.MaterialName = "Material1";
a.ListMyClass.Add( new MyClass1 { id = 11,Name="Name1" });
a.ListMyClass.Add(new MyClass1 { id = 12, Name = "Name2" });
b.CwNumber = "A";
b.MaterialId = 2;
b.MaterialName = "Material2";
b.ListMyClass.Add(new MyClass1 { id = 21, Name = "Name3" });
b.ListMyClass.Add(new MyClass1 { id = 22, Name = "Name4" });
List<Variance> rt = a.GetDiffValue(b);
}
public List<Variance> GetDiffValue<T>(this T val1, T val2)
{
List<Variance> variances = new List<Variance>();
Variance v = new Variance();
PropertyInfo[] pi = val1.GetType().GetProperties();
foreach (PropertyInfo p in pi)
{
Variance v1 = new Variance();
if (p.PropertyType.IsGenericType == true)
{
v1.Prop = p.Name;
v1.valA = p.GetValue(val1, null);
v1.valB = p.GetValue(val2, null);
}
else
{
v1.Prop = p.Name;
v1.valA = p.GetValue(val1,null);
v1.valB = p.GetValue(val2,null);
}
if (!v1.valA.Equals(v1.valB))
{
variances.Add(v);
}
}
return variances;
}
}
public class SomeCustomClass
{
public int MaterialId { get; set; }
public string CwNumber { get; set; }
public List<MyClass1> ListMyClass { get; set; }
public UsesModel Uses { get; set; }
public SomeCustomClass()
{
ListMyClass = new List<MyClass1>();
}
}
public class MyClass1
{
public int id;
string Name;
}
public class Variance
{
public string propertyName { get; set; }
public object OldValue { get; set; }
public object NewValue { get; set; }
}