Recently, when Refix supports the import and export function of Excel files, I found that it is useful to use reflection-related skills. Therefore, I checked some information on the Internet and deepened my understanding through code debugging.
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; } } }
The code mainly uses GetType(), GetValue(), and SetValue(), but it is easy to make mistakes in the application, especially when the type is converted.
Make a memo here and follow up.