C#反射比较具有布尔属性的2个对象

时间:2018-10-29 19:36:47

标签: c# object reflection

我有两个对象,它们具有几个布尔类型的属性。 这些属性在命名方面是相同的,我只想确保它们相等。我做了很多这样的检查,想知道是否有人建议一种方法,可以一步执行以下代码,但是具有足够的动态性,可以按名称检查属性选项(如果它们具有相同的名称)?

 if (options != null && other != null)
            return options.Quantities == other.Quantities &&
                   options.SKUEntityKey == other.SKUEntityKey &&
                   options.LineItemType_Type == other.LineItemType_Type &&
                   options.SKUIdentifier == other.SKUIdentifier &&
                   options.Identifier == other.Identifier;

如果我的要求不清楚,请告诉我

2 个答案:

答案 0 :(得分:0)

   class Program
    {
        static void Main(string[] args)
        {
            ReflectOverProperties<TestClass, TestClass2>(new TestClass(), new TestClass2());
            Console.ReadLine();
        }

        public static void ReflectOverProperties<T, Z>(T x, Z y)
        {
            var properties = typeof(T).GetProperties();
            foreach (var item in properties)
            {
                CompareProperty(x, y, item.Name);

            }
        }

        private static void CompareProperty<T, Z>(T x, Z y, string itemName)
        {
            dynamic originalValue = GetPropValue(x, itemName);
            dynamic newValue = GetPropValue(y, itemName);
            PropertyCompare(itemName, originalValue, newValue);

        }

        private static void PropertyCompare(string itemName, dynamic originalValue, dynamic newValue)
        {
            if (originalValue != newValue)
            {
             Console.Write($"Property {itemName} does not match");
            }
        }



        public static object GetPropValue(object src, string propName)
        {
            return src.GetType().GetProperty(propName).GetValue(src, null);
        }
    }

    public class TestClass
    {
        public TestClass()
        {
            Test1 = false;
            Test2 = false;
            Test3 = false;
        }
        public bool Test1 { get; set; }
        public bool Test2 { get; set; }
        public bool Test3 { get; set; }
    }
    public class TestClass2
    {
        public TestClass2()
        {
            Test1 = false;
            Test2 = false;
            Test3 = true;
        }
        public bool Test1 { get; set; }
        public bool Test2 { get; set; }
        public bool Test3 { get; set; }
    }

这是我快速修改的一些代码,可在控制台应用程序中运行。希望将您设置在正确的方向上,现在做相同的对象可能会有所不同。仅使用一些基本的反射和动态属性。

答案 1 :(得分:0)

我希望这个可怕的控制台应用程序至少可以让您对如何做自己想做的事情有所了解:

    static void Main(string[] args)
    {
        Person steve = new Person()
        {
            IsHungry = true,
            IsLazy = false,
            IsSleepy = true
        };

        Dog bella= new Dog()
        {
            IsHungry = true,
            IsLazy = false,
            IsSleepy = true
        };

        bool match = DoAllBoolPropertiesMatch(steve, bella);

        Console.WriteLine($"\r\n----> Do Bools in Objects Match?: {match}");
    }

    private static bool DoAllBoolPropertiesMatch(object obj1, object obj2)
    {
        // For each Boolean property of object 1, check object 2:
        foreach(PropertyInfo propInfo in obj1.GetType().GetProperties())
        {
            // Property is boolean.
            if(propInfo.PropertyType == typeof(Boolean))
            {
                // Look for a property on obj2 with the same name that also returns a bool.
                PropertyInfo matchingPropInfo = obj2.GetType().GetProperty(propInfo.Name, typeof(Boolean));

                if(matchingPropInfo != null)
                {
                    Console.WriteLine($"Evaluating Property {propInfo.Name} from obj1:");
                    Console.WriteLine($"  - Value for Obj1 = [{propInfo.GetValue(obj1)}]");
                    Console.WriteLine($"  - Value for Obj2 = [{matchingPropInfo.GetValue(obj2)}]");

                    if(Convert.ToBoolean(propInfo.GetValue(obj1)) != Convert.ToBoolean(matchingPropInfo.GetValue(obj2)))
                        return false;
                }
            }
        }

        return true;
    }

    public class Person
    {
        public bool IsHungry { get; set; }
        public bool IsSleepy { get; set; }
        public bool IsLazy { get; set; }
    }

    public class Dog
    {
        public bool IsHungry { get; set; }
        public bool IsSleepy { get; set; }
        public bool IsLazy { get; set; }
    }