zoukankan      html  css  js  c++  java
  • 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(),不过在应用中比较容易出错,尤其是类型转换的时候。

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

    墨匠
  • 相关阅读:
    android数据恢复
    UVA 690 Pipeline Scheduling
    2017 国庆湖南 Day4
    2017 国庆湖南 Day5
    2017 国庆湖南 Day6
    2017国庆 清北学堂 北京综合强化班 Day1
    2017 国庆湖南Day2
    bzoj 2962 序列操作
    UVA 818 Cutting Chains
    UVA 211 The Domino Effect
  • 原文地址:https://www.cnblogs.com/Jashinck/p/8922353.html
Copyright © 2011-2022 走看看