反射操作辅助类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 ...
随机推荐
- html_day1
第一天学习,了解到html的结构和语法. html的语法: 1.所有的html标签都要放在<>尖括号里. 2.标签不分大小写 建议小写 3.标签中的属性与标签名之间要有一个空格,如多个 ...
- CSS的优先级
样式的优先级: (内联样式表[嵌入式样式])>(内部样式表)>(外部样式表) 经过测试动手测试发现有个(唯一的)例外 情况:当引用外部样式在内部样式表(非嵌入式样式)的后面时,外部样式会覆 ...
- NSNotification消息
注册消息 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(方法) name:@"消息名字&q ...
- Random获得的随机数怎么样减少重复率
C#中的Random在获得随机数的时,如果你想要随机循环取得100个随机数则使用如下代码会出现大量的重复数字.代码如下: using System; namespace ConsoleApplicat ...
- zongjie
$msg = $_GET['msg'];$startDate = $_POST['startDate'];$endDate = $_POST['endDate'];$quickdate = $_POS ...
- 实现js浮点数加、减、乘、除的精确计算(网上很多文章里的方法是不能解决所有js浮点数计算误差的)
最近做项目,要用到js的加.减.乘.除的计算,发现js浮点数计算会有一些误差. 网上有很多文章都有js浮点数计算误差的解决方法,说能解决这个问题,But…….比如一个加法函数,如下: function ...
- js经典代码技巧学习之一:使用三元运算符处理javascript兼容
window.Event = { add: function() { //使用条件表达式检测标准方法是否存在 return document.addEventListener ? function(a ...
- tuple只有一个元素的时候,必须要加逗号
In [1]: a = (1) In [2]: a Out[2]: 1 In [3]: a = (1,) In [4]: a Out[4]: (1,) 这是因为括号()既可以表示tuple,又可以表示 ...
- You and your research
英文版http://www.cs.virginia.edu/~robins/YouAndYourResearch.html 视频版http://www.youtube.com/watch?v=a1zD ...
- DeflateStream类
DeflateStream是另外一种压缩与解压缩流,使用方法与GZipStream类似,而且压缩之后的带下也差不多. 一.属性 BaseStream 获取对基础流的引用. CanRead 获取一个值 ...