我有一个相当复杂的模型类,我需要将其与相同类型的另一个类进行比较。我已经使用反射实现了一个比较函数,但是其中一个类将具有四舍五入到整数的值,而另一个类将具有双精度值。我需要将所有这些双精度值四舍五入到最接近的整数,以便我的比较函数工作。
正在讨论的Compare函数:
public static List<Variance> DetailedCompare<Type>(this Type saveModel, Type loadModel)
{
List<Variance> variancesList = new List<Variance>();
PropertyInfo[] fieldList = saveModel.GetType().GetProperties();
foreach (PropertyInfo field in fieldList)
{
if (!ignoreList.Contains(field.Name))
{
Variance variance = new Variance();
variance.property = field.Name;
variance.saveValue = field.GetValue(saveModel, null);
variance.loadValue = field.GetValue(loadModel, null);
if (!Equals(variance.saveValue, variance.loadValue))
variancesList.Add(variance);
}
}
return variancesList;
}
需要比较的模型类:
public class DisplayModel
{
public Point topLeft { get; set; }
public Point bottomRight { get; set; }
public double? intercept { get; set; }
}
public class Point
{
public double x { get; set; }
public double y { get; set; }
}
是否有一种方法可以遍历对象属性并检查它们是否为double类型,或者是否需要手动更改每个属性?
编辑:更具体一点,我大多有嵌套复杂类型的麻烦。检查变量,如intercept并不是太糟糕,但我不确定什么是最好的方法来处理像topLeft和bottomRight这样的事情。还有像Point这样的复杂类型,但具有不同的属性名称,所以理想情况下我宁愿不直接检查Point对象。
可以使用PropertyType:
if (field.PropertyType == typeof(double))
https://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo (v = vs.110) . aspx
https://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.propertytype (v = vs.110) . aspx
<更新:例子/strong>
class Test1{
public int t1 {get; set;}
public string t2 {get; set;}
public Type t3 {get; set;}
public bool t4 {get; set;}
public double t5 {get; set;}
public float t6 {get; set;}
public double field;
}
void Main()
{
PrintProps(new Test1());
PrintProps(new System.Drawing.Point());
}
private static void PrintProps(object o){
Console.WriteLine("Begin: " + o.GetType().FullName);
var t = o.GetType();
var props = t.GetProperties(BindingFlags.Public |
BindingFlags.Instance); // you can do same with GetFields();
foreach(var p in props){
Console.WriteLine(string.Format("{0} = {1}", p.Name,p.PropertyType == typeof(double)));
}
Console.WriteLine("End");
}
样本输出:
Begin: UserQuery+Test1
t1 = False
t2 = False
t3 = False
t4 = False
t5 = True
t6 = False
End
Begin: System.Drawing.Point
IsEmpty = False
X = False
Y = False
End