C#使用反射设置属性值

最近在Refix一个支持Excel文件导入导出功能时,发现有用到反射的相关技能。故而在网上查了些资料,通过代码调试加深下理解。

    class Program
    {
        static void Main(string[] args)
        {
            var student = new Student() { Name = "Jack", Address = "Lingbi County", City = "Zhangyuan" };
            var studentName = GetModelValue("Name", student);
            var studentCity = SetModelValue("City", "Wuhan", student);
            Console.WriteLine($"Hello World! {student.Name}, {student.City}");
            
        }

        /// <summary>
        /// 获取类中的属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetModelValue(string FieldName, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object o = Ts.GetProperty(FieldName).GetValue(obj, null);
                string Value = Convert.ToString(o);
                if (string.IsNullOrEmpty(Value)) return null;
                return Value;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 设置类中的属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SetModelValue(string FieldName, string Value, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType);
                Ts.GetProperty(FieldName).SetValue(obj, v, null);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public class Student
        {
            public string Name { get; set; }
            public string Address { get; set; }
            public string City { get; set; }
        }
    }

代码中主要使用到GetType(), GetValue(), 以及SetValue(),不过在应用中比较容易出错,尤其是类型转换的时候。

在此做个备忘录,后续持续跟进。

猜你喜欢

转载自www.cnblogs.com/Jashinck/p/8922353.html