反射操作辅助类ReflectionUtil
这篇文章的目的是介绍这样一种方式,就是在写一个函数的时候,传递的参数是object类型的,在这个函数里面想访问这个参数对象的某一属性值,我们知道这个属性值的name,但是一般情况下,object对象是没法获取具体属性的值的,所以用下面的方式可以获取。此文章为转载,原文在:http://lsyyxcn.blog.163.com/blog/static/22740531201002792629559/
/// <summary>
/// 反射操作辅助类
/// </summary>
public sealed class ReflectionUtil
{
private ReflectionUtil()
{
} private static BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; /**//// <summary>
/// 执行某个方法
/// </summary>
/// <param name="obj">指定的对象</param>
/// <param name="methodName">对象方法名称</param>
/// <param name="args">参数</param>
/// <returns></returns>
public static object InvokeMethod(object obj, string methodName, object[] args)
{
object objResult = null;
Type type = obj.GetType();
objResult = type.InvokeMember(methodName, bindingFlags | BindingFlags.InvokeMethod, null, obj, args);
return objResult;
} /**//// <summary>
/// 设置对象字段的值
/// </summary>
public static void SetField(object obj, string name, object value)
{
FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
object objValue = Convert.ChangeType(value, fieldInfo.FieldType);
fieldInfo.SetValue(objValue, value);
} /**//// <summary>
/// 获取对象字段的值
/// </summary>
public static object GetField(object obj, string name)
{
FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
return fieldInfo.GetValue(obj);
} /**//// <summary>
/// 设置对象属性的值
/// </summary>
public static void SetProperty(object obj, string name, object value)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
propertyInfo.SetValue(obj, objValue, null);
} /**//// <summary>
/// 获取对象属性的值
/// </summary>
public static object GetProperty(object obj, string name)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
return propertyInfo.GetValue(obj, null);
} /**//// <summary>
/// 获取对象属性信息(组装成字符串输出)
/// </summary>
public static string GetProperties(object obj)
{
StringBuilder strBuilder = new StringBuilder();
PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bindingFlags); foreach (PropertyInfo property in propertyInfos)
{
strBuilder.Append(property.Name);
strBuilder.Append(":");
strBuilder.Append(property.GetValue(obj, null));
strBuilder.Append("\r\n");
} return strBuilder.ToString();
}
} 反射操作辅助类ReflectionUtil测试代码:
public class TestReflectionUtil
{
public static string Execute()
{
string result = string.Empty;
result += "使用ReflectionUtil反射操作辅助类:" + "\r\n"; try
{
Person person = new Person();
person.Name = "wuhuacong";
person.Age = ;
result += DecriptPerson(person); person.Name = "Wade Wu";
person.Age = ;
result += DecriptPerson(person);
}
catch (Exception ex)
{
result += string.Format("发生错误:{0}!\r\n \r\n", ex.Message);
}
return result;
} public static string DecriptPerson(Person person)
{
string result = string.Empty; result += "name:" + ReflectionUtil.GetField(person, "name") + "\r\n";
result += "age" + ReflectionUtil.GetField(person, "age") + "\r\n"; result += "Name:" + ReflectionUtil.GetProperty(person, "Name") + "\r\n";
result += "Age:" + ReflectionUtil.GetProperty(person, "Age") + "\r\n"; result += "Say:" + ReflectionUtil.InvokeMethod(person, "Say", new object[] {}) + "\r\n"; result += "操作完成!\r\n \r\n"; return result;
}
}
/// <summary>
/// 反射操作辅助类
/// </summary>
public sealed class ReflectionUtil
{
private ReflectionUtil()
{
}
private static BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
/**//// <summary>
/// 执行某个方法
/// </summary>
/// <param name="obj">指定的对象</param>
/// <param name="methodName">对象方法名称</param>
/// <param name="args">参数</param>
/// <returns></returns>
public static object InvokeMethod(object obj, string methodName, object[] args)
{
object objResult = null;
Type type = obj.GetType();
objResult = type.InvokeMember(methodName, bindingFlags | BindingFlags.InvokeMethod, null, obj, args);
return objResult;
}
/**//// <summary>
/// 设置对象字段的值
/// </summary>
public static void SetField(object obj, string name, object value)
{
FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
object objValue = Convert.ChangeType(value, fieldInfo.FieldType);
fieldInfo.SetValue(objValue, value);
}
/**//// <summary>
/// 获取对象字段的值
/// </summary>
public static object GetField(object obj, string name)
{
FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
return fieldInfo.GetValue(obj);
}
/**//// <summary>
/// 设置对象属性的值
/// </summary>
public static void SetProperty(object obj, string name, object value)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
propertyInfo.SetValue(obj, objValue, null);
}
/**//// <summary>
/// 获取对象属性的值
/// </summary>
public static object GetProperty(object obj, string name)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
return propertyInfo.GetValue(obj, null);
}
/**//// <summary>
/// 获取对象属性信息(组装成字符串输出)
/// </summary>
public static string GetProperties(object obj)
{
StringBuilder strBuilder = new StringBuilder();
PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bindingFlags);
foreach (PropertyInfo property in propertyInfos)
{
strBuilder.Append(property.Name);
strBuilder.Append(":");
strBuilder.Append(property.GetValue(obj, null));
strBuilder.Append("\r\n");
}
return strBuilder.ToString();
}
}
反射操作辅助类ReflectionUtil测试代码:
public class TestReflectionUtil
{
public static string Execute()
{
string result = string.Empty;
result += "使用ReflectionUtil反射操作辅助类:" + "\r\n";
try
{
Person person = new Person();
person.Name = "wuhuacong";
person.Age = 20;
result += DecriptPerson(person);
person.Name = "Wade Wu";
person.Age = 99;
result += DecriptPerson(person);
}
catch (Exception ex)
{
result += string.Format("发生错误:{0}!\r\n \r\n", ex.Message);
}
return result;
}
public static string DecriptPerson(Person person)
{
string result = string.Empty;
result += "name:" + ReflectionUtil.GetField(person, "name") + "\r\n";
result += "age" + ReflectionUtil.GetField(person, "age") + "\r\n";
result += "Name:" + ReflectionUtil.GetProperty(person, "Name") + "\r\n";
result += "Age:" + ReflectionUtil.GetProperty(person, "Age") + "\r\n";
result += "Say:" + ReflectionUtil.InvokeMethod(person, "Say", new object[] {}) + "\r\n";
result += "操作完成!\r\n \r\n";
return result;
}
}
反射操作辅助类ReflectionUtil的更多相关文章
- Java的几个同步辅助类
Java为我们提供了一些同步辅助类,利用这些辅助类我们可以在多线程编程中,灵活地把握线程的状态. CountDownLatch CountDownLatch一个同步辅助类,在完成一组正在其他线程中执行 ...
- ASP.NET Core 中文文档 第四章 MVC(3.6.2 )自定义标签辅助类(Tag Helpers)
原文:Authoring Tag Helpers 作者:Rick Anderson 翻译:张海龙(jiechen) 校对:许登洋(Seay) 示例代码查看与下载 从 Tag Helper 讲起 本篇教 ...
- DateHelper.cs日期时间操作辅助类C#
//==================================================================== //** Copyright © classbao.com ...
- 同步辅助类CountDownLatch用法
CountDownLatch是一个同步辅助类,犹如倒计时计数器,创建对象时通过构造方法设置初始值,调用CountDownLatch对象的await()方法则使当前线程处于等待状态,调用countDow ...
- 基于MemoryCache的缓存辅助类
背景: 1. 什么是MemoryCache? memoryCache就是用电脑内存做缓存处理 2.使用范围? 可用于不常变的数据,进行保存在内存中,提高处理效率 代码: /// <summary ...
- java中被各种XXUtil/XXUtils辅助类恶心到了,推荐这种命名方法
且看一下有多少个StringUtils 列举一下XXUtil/XXUtils恶劣之处 1. 不知道该用XXUtil还是用XXUtils, 或者XXHelper, XXTool 2. 不知道该用a.ja ...
- NPOI操作Excel辅助类
/// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...
- ByteBuf和相关辅助类
当我们进行数据传输的时候,往往需要使用到缓冲区,常用的缓冲区就是JDK NIO类库提供的java.nio.Buffer. 实际上,7种基础类型(Boolean除外)都有自己的缓冲区实现,对于NIO编程 ...
- Bootstrap<基础九>辅助类
Bootstrap 中的一些可能会派上用场的辅助类. 文本 以下不同的类展示了不同的文本颜色.如果文本是个链接鼠标移动到文本上会变暗: 类 描述 .text-muted "text-mu ...
随机推荐
- 手机版和PC版识别
1.C#通过User-Agent 处理 //判断 是否来自手机终端 public bool checkMoble() { string userAgent = Request.Headers[&qu ...
- Ubutu命令 笔记积累
1 man command 查询帮助 查询结果会有 name synopsis(概要) description 2 terminal 中快捷键: Ctrl +u 撤销 Ctrl +l 清屏 ...
- CISC + RISC = Y86
最近在读深入理解计算机系统,打算把读时的心得放上来 Y86有着CISC和RISC的属性Y86可以看成是CISC(IA32),但用RISC的原理简化了 CISC和RISC的竞争引发了许多争论CISC和R ...
- 跨平台渲染框架尝试 - constant buffer的管理
1. Preface Constant buffer是我们在编写shader的时候,打交道最多的一种buffer resource了.constant表明了constant buffer中的数据,在一 ...
- [ofbiz]service中OUT的定义
在service中返回的任何一个结果,比如map1,map2,然后这两个map又封装在另一个map中,则service的定义中,要将map1和map2定义为OUT类型 LOFTER:我们的故事 h ...
- winform 读取保存配置文件
原文连接: public static string fileName = System.IO.Path.GetFileName(Application.ExecutablePath); ...
- Common-logging 与 Log4j的结合使用
分类: Java 一.结合说明 在我们的日常开发中,经常需要通过输出一些信息进行程序的调试,如果到处都用system.out.println()则在项目发布之后要逐一删除,而log4j提供了一种新的调 ...
- 远程复制 scp命令
定义 本机为A,用户名为usera,登录远程主机B的为userb,IP为remote_ip 1. 从B 拷贝文件到A机器 用下面的命令 scp userb@remote_ip:remote_path ...
- [C++程序设计]用指向数组的指针作函数参数
#include <iostream> using namespace std; int main() { ]); ][]={,,,,,,,,,,,}; output(a); ; } ]) ...
- java类中的static成员变量和static方法简单介绍,持续补充
一.静态成员变量 1.属于整个类而不是某个对象实例,所以可以直接通过类名和对象名去调用. 2.静态成员属于整个类,当系统第一次使用该类时,就会为其分配内存空间直到该类被卸载才会进行资源回收 二.静态方 ...