C# 通过反射获取类型的字段值及给字段赋值的操作
作者:qq_40693302 时间:2021-11-14 13:30:23
举例:
存在一个类:
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
标签:C#,反射,字段值,赋值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解JAVA中的OPTIONAL
2022-08-22 17:09:04
![](https://img.aspxhome.com/file/2023/1/64001_0s.png)
Java并发编程示例(七):守护线程的创建和运行
2023-11-25 11:39:32
spring boot微服务场景下apollo加载过程解析
2022-05-20 13:55:32
C语言高效编程的几招小技巧
2023-11-02 14:12:50
Spring Security 实现用户名密码登录流程源码详解
2023-05-31 11:13:59
![](https://img.aspxhome.com/file/2023/8/64058_0s.png)
简单谈谈Java 中的线程的几种状态
2023-05-10 13:29:45
Java可变个数形参的方法实例代码
2023-01-15 18:35:56
![](https://img.aspxhome.com/file/2023/2/62372_0s.png)
Spring如何处理注解的深入理解
2023-09-09 14:35:49
Java 调用天气Webservice详解及实例代码
2021-10-09 21:59:03
Java远程连接Linux服务器并执行命令及上传文件功能
2023-01-28 14:03:31
C# 添加对System.Configuration.dll文件的引用操作
2022-03-05 22:20:31
![](https://img.aspxhome.com/file/2023/7/69807_0s.jpg)
Flutter 如何正确显示SnackBar
2023-06-23 13:00:40
Java定位问题线程解析
2023-08-09 22:04:27
![](https://img.aspxhome.com/file/2023/1/58041_0s.png)
C#中应用程序集的装载过程详解
2023-03-30 19:06:05
![](https://img.aspxhome.com/file/2023/5/68065_0s.png)
Java Map集合用法详解
2023-08-01 14:47:01
![](https://img.aspxhome.com/file/2023/2/63652_0s.png)
详解java整合solr5.0之solrj的使用
2023-07-23 03:12:06
![](https://img.aspxhome.com/file/2023/3/57493_0s.png)
Java执行SQL脚本文件到数据库详解
2023-08-08 08:30:00
springboot搭建访客管理系统的实现示例
2023-09-02 13:10:41
![](https://img.aspxhome.com/file/2023/3/58463_0s.png)
Swing拆分窗格控件JSplitPane使用详解
2022-11-14 21:13:48
![](https://img.aspxhome.com/file/2023/0/63500_0s.jpg)
Java流处理stream使用详解
2021-09-17 18:27:58