天天看點

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; }

        }

繼續閱讀