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

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

    墨匠
  • 相关阅读:
    压缩感知中的lp球:p范数最优化为什么总会导致一个稀疏的解的原因
    有限等距性质RIP
    P问题、NP问题、NPC问题
    浅读K-means
    Python初学——pickle & set
    Python初学——窗口视窗Tkinter
    Python初学——多进程Multiprocessing
    暴力【bzoj2208】: [Jsoi2010]连通数
    打表数学【bzoj2173】: 整数的lqp拆分
    最短路【bzoj1726】: [Usaco2006 Nov]Roadblocks第二短路
  • 原文地址:https://www.cnblogs.com/Jashinck/p/8922353.html
Copyright © 2011-2022 走看看