C# --通过反射获取类型的字段值及给字段赋值

转自:

https://blog.csdn.net/qq_40693302/article/details/98961669

以下是转载的,方便自己快速查阅,这篇文章总结的很好,感谢原作者。

举例:
存在一个类:

Public Class Student
{
	public string name;
	public int age;
}
Student stu1 = new Student();

  

现在,我们想通过反射在运行时给stu1的name 和 age字段 赋值,让name = “小明”,age = 15,怎么做?
简单的代码如下:

...略
using System.Reflection;//反射类
...略
static void Main(string[] args)
{
	Type t = stu1.GetType();
	FieldInfo filedInfo1 =  t.GetField(”name");
	FieldInfo filedInfo2 =  t.GetField(”age");
	fieldInfo1.SetValue(stu1,"小明");
	fieldInfo2.SetValue(stu1,15);
} 

  

需要注意的是:FieldInfo的SetValue方法有可能会导致异常,比如 fieldInfo2.SetValue(stu1,“15”),这句话给一个int型字段赋了string类型的值,编译是不会报错的,在运行时会抛出一个System.ArgumentException异常,请多加注意.

有了以上的了解,让我们写一个简单的动态字段赋值/取值类Dynamic

具体代码如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace MyUnityHelper
{
    /// <summary>
    /// 动态编译类
    /// </summary>
    public class Dynamic
    {
        /// <summary>
        /// 动态赋值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        public static void SetValue(object obj,string fieldName,object value)
        {
           FieldInfo info =  obj.GetType().GetField(fieldName);
           info.SetValue(obj, value);
        }
        /// <summary>
        /// 泛型动态赋值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        public static void SetValue<T>(object obj, string fieldName, T value)
        {
            FieldInfo info = obj.GetType().GetField(fieldName);
            info.SetValue(obj, value);
        }
        /// <summary>
        /// 动态取值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public static object GetValue(object obj, string fieldName)
        {
            FieldInfo info = obj.GetType().GetField(fieldName);
            return info.GetValue(obj);
        }
        /// <summary>
        /// 动态取值泛型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public static T GetValue<T>(object obj,string fieldName)
        {
            FieldInfo info = obj.GetType().GetField(fieldName);
            return (T)info.GetValue(obj);
        }
    }
}

  


————————————————
版权声明:本文为CSDN博主「qq_40693302」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_40693302/article/details/98961669

posted @ 2021-09-12 14:31  包子789654  阅读(1515)  评论(0编辑  收藏  举报