检查类是否包含double类型的任何属性并将它们转换为整数

时间:2015-05-26 21:39:39

标签: c# reflection

我有一个相当复杂的模型类,我需要与另一个相同类型的类进行比较。我已经使用反射实现了一个比较函数,但其​​中一个类的值将四舍五入为整数,另一个类的值为双精度值。我需要将所有这些double值舍入到最接近的整数,以便我的比较函数能够工作。

有问题的比较功能:

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类型,或者是否需要手动更改每个属性?

编辑:为了更具体一点,我主要遇到嵌套复杂类型的问题。检查拦截等变量并不算太糟糕,但我不确定处理topLeft和bottomRight等事情的最佳方法是什么。还有像Point这样的复杂类型,但是具有不同的属性名称,所以理想情况下我不会直接检查Point对象。

1 个答案:

答案 0 :(得分:1)

您可以使用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

更新:示例

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