我有以下课程:
public class Person
{
public String FirstName { set; get; }
public String LastName { set; get; }
public Role Role { set; get; }
}
public class Role
{
public String Description { set; get; }
public Double Salary { set; get; }
public Boolean HasBonus { set; get; }
}
我希望能够自动提取Person1和Person2之间的属性值差异,例如如下:
public static List<String> DiffObjectsProperties(T a, T b)
{
List<String> differences = new List<String>();
foreach (var p in a.GetType().GetProperties())
{
var v1 = p.GetValue(a, null);
var v2 = b.GetType().GetProperty(p.Name).GetValue(b, null);
/* What happens if property type is a class e.g. Role???
* How do we extract property values of Role?
* Need to come up a better way than using .Namespace != "System"
*/
if (!v1.GetType()
.Namespace
.Equals("System", StringComparison.OrdinalIgnoreCase))
continue;
//add values to differences List
}
return differences;
}
如何提取Role in Person ???的属性值
答案 0 :(得分:2)
public static List<String> DiffObjectsProperties(object a, object b)
{
Type type = a.GetType();
List<String> differences = new List<String>();
foreach (PropertyInfo p in type.GetProperties())
{
object aValue = p.GetValue(a, null);
object bValue = p.GetValue(b, null);
if (p.PropertyType.IsPrimitive || p.PropertyType == typeof(string))
{
if (!aValue.Equals(bValue))
differences.Add(
String.Format("{0}:{1}!={2}",p.Name, aValue, bValue)
);
}
else
differences.AddRange(DiffObjectsProperties(aValue, bValue));
}
return differences;
}
答案 1 :(得分:1)
如果属性不是值类型,为什么不直接在它们上调用DiffObjectProperties并将结果追加到当前列表?据推测,您需要遍历它们并以点表示法前置属性的名称,以便您可以看到不同的内容 - 或者可能足以知道如果列表非空,则当前属性不同
答案 2 :(得分:0)
因为我不知道如何辨别:
var v1 = p.GetValue(a, null);
是String FirstName或Role Role。我一直试图找出如何判断v1是否是一个字符串,如FirstName或类Role。因此,我不知道何时递归地将对象属性(Role)传递回DiffObjectsProperties以迭代其属性值。