天天看点

C# 通过属性赋值(反射)

 [TestMethod]

        public void TestMethod2()

        {

            //key-value列表

            var user1KeyValues = new List<User1KeyValue>() { new User1KeyValue() { Key = "Exception", Value = "1" } };

            var user = new User();

            user1KeyValues.ForEach(user1KeyValue =>

            {

                //获取特性

                var property = user.GetType().GetProperty(user1KeyValue.Key);

                //根据特性自动转换值类型

                object value= Convert.ChangeType(user1KeyValue.Value, (Nullable.GetUnderlyingType(property?.PropertyType) ?? property?.PropertyType));

                //赋值

                property?.SetValue(user, value);

            });

        }

 public class User

        {

            public int Exception { get; set; }

        }

        public class User1KeyValue

        {

            public string Key { get; set; }

            public string Value { get; set; }

        }

继续阅读