软件编程
位置:首页>> 软件编程>> C#编程>> C# 通过反射获取类型的字段值及给字段赋值的操作

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

作者:qq_40693302  发布时间:2021-11-14 13:30:23 

标签:C#,反射,字段值,赋值

举例:

存在一个类:


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);
 }
}
}

补充:C#利用反射方法实现对象的字段和属性之间值传递

在面向对象开发过程中,往往会遇到两个对象之间进行值传递的情况,如果对象中的属性和字段较多,手动一一赋值效率实在太低。

这里就整理了一个通用的对象之间进行值传递的方法,并且考虑到对象中可能包含类属性,因此还用到了递归以解决这个问题。

下面上代码:


public static void ConvertObject(object SrcClass, object DesClass, bool convertProperty = true, bool convertField = true, bool showError = true)
 {
  try
  {
   if (SrcClass == null)
   {
    return;
   }
   if (convertProperty)
   {
    PropertyInfo[] srcProperties = SrcClass.GetType().GetProperties();
    PropertyInfo[] desProperties = DesClass.GetType().GetProperties();
    if (srcProperties.Length > 0 && desProperties.Length > 0)
    {
     foreach (var srcPi in srcProperties)
     {
      foreach (var desPi in desProperties)
      {
       if (srcPi.Name == desPi.Name && srcPi.PropertyType == desPi.PropertyType && desPi.CanWrite)
       {
        if (srcPi.PropertyType.IsClass)
        {
         ConvertObject(srcPi.GetValue(SrcClass, null), desPi.GetValue(DesClass, null), convertProperty, convertField, showError);
        }
        else
        {
         Object value = srcPi.GetValue(SrcClass, null);
         desPi.SetValue(DesClass, value, null);
        }
       }
      }
     }
    }
   }
   if (convertField)
   {
    FieldInfo[] srcFields = SrcClass.GetType().GetFields();
    FieldInfo[] desFields = DesClass.GetType().GetFields();
    if (srcFields.Length > 0 && desFields.Length > 0)
    {
     foreach (var srcField in srcFields)
     {
      foreach (var desField in desFields)
      {
       if (srcField.Name == desField.Name && srcField.FieldType == desField.FieldType)
       {
        if (srcField.FieldType.IsClass)
        {
         ConvertObject(srcField.GetValue(SrcClass), desField.GetValue(DesClass), convertProperty, convertField, showError);
        }
        else
        {
         Object value = srcField.GetValue(SrcClass);
         desField.SetValue(DesClass, value);
        }
       }
      }
     }
    }
   }
  }
  catch (Exception ex)
  {
   if (showError)
   {
    MessageBox.Show($"Convert Error: Method={nameof(ConvertObject)}, Message={ex.Message}");
   }
   else
   {
    throw new Exception($"Convert Error: Method={nameof(ConvertObject)}, Message={ex.Message}");
   }
  }
 }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com