轉自:
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
