用反射獲取和設置嵌套屬性



get or set values of the Nested Property using C# Reflection

        private void button2_Click(object sender, EventArgs e)
        {
            Person p1 = new Person();
            Customer c1 = new Customer { Title = "tt", Surname = "ss" };
            p1.Bill = c1;
            object pp = GetPropValue("Bill.Title", p1);
            this.Text = pp.ToString();
            SetProperty("Bill.Title", p1,"pi1");
            object pp1 = GetPropValue("Bill.Title", p1);
            this.Text = pp1.ToString();
            PropertyInfo pi1 = GetProp(p1.GetType(), "Bill.Title");           
        }
        public class Person
        {
            public Customer Bill { get; set; }

        }
        public class Customer
        {
            public string Title { get; set; }
            public string Surname { get; set; }
        }
        public Object GetPropValue(String name, Object obj)
        {
            foreach (String part in name.Split('.'))
            {
                if (obj == null) { return null; }

                Type type = obj.GetType();
                PropertyInfo info = type.GetProperty(part);
                if (info == null) { return null; }

                obj = info.GetValue(obj, null);
            }
            return obj;
        }
        public PropertyInfo GetProp(Type baseType, string propertyName)
        {
            string[] parts = propertyName.Split('.');

            return (parts.Length > 1)
                ? GetProp(baseType.GetProperty(parts[0]).PropertyType, parts.Skip(1).Aggregate((a, i) => a + "." + i))
                : baseType.GetProperty(propertyName);
        }
        private static System.Reflection.PropertyInfo GetProperty(object t, string PropertName)
        {
            if (t.GetType().GetProperties().FirstOrDefault(p => p.Name == PropertName.Split('.')[0]) == null)
                throw new ArgumentNullException(string.Format("Property {0}, is not exists in object {1}", PropertName, t.ToString()));
            if (PropertName.Split('.').Length == 1)
                return t.GetType().GetProperty(PropertName);
            else
                return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Split('.')[1]);
        }
        public void SetProperty(string compoundProperty, object target, object value)
        {
            string[] bits = compoundProperty.Split('.');
            for (int i = 0; i < bits.Length - 1; i++)
            {
                PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]);
                target = propertyToGet.GetValue(target, null);
            }
            PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last());
            propertyToSet.SetValue(target, value, null);
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章