C#反射技术的简单操作(读取和设置类的属性)

所属分类: 网络编程 / ASP.NET 阅读数: 410
收藏 0 赞 0 分享

要想对一个类型实例的属性或字段进行动态赋值或取值,首先得得到这个实例或类型的Type,微软已经为我们提供了足够多的方法。
首先建立一个测试的类

复制代码 代码如下:

public class MyClass
{
public int one { set; get; }
public int two { set; get; }
public int five { set; get; }
public int three { set; get; }
public int four { set; get; }
}

然后编写反射该类的代码
复制代码 代码如下:

MyClass obj = new MyClass();
Type t = typeof(MyClass);
//循环赋值
int i = 0;
foreach (var item in t.GetProperties())
{
item.SetValue(obj, i, null);
i += 1;
}
//单独赋值
t.GetProperty("five").SetValue(obj, 11111111, null);
//循环获取
StringBuilder sb = new StringBuilder();
foreach (var item in t.GetProperties())
{
sb.Append("类型:" + item.PropertyType.FullName + " 属性名:" + item.Name + " 值:" + item.GetValue(obj, null) + "<br />");
}
//单独取值
int five = Convert.ToInt32(t.GetProperty("five").GetValue(obj, null));
sb.Append("单独取five的值:" + five);
string result = sb.ToString();
Response.Write(result);

测试显示结果:
类型:System.Int32 属性名:one 值:0
类型:System.Int32 属性名:two 值:1
类型:System.Int32 属性名:five 值:11111111
类型:System.Int32 属性名:three 值:3
类型:System.Int32 属性名:four 值:4
单独取five的值:11111111

好了,了解了类的属性反射使用后,聪明的你可能就想到了方法也是可以这样做的,即t.GetProperties()改为t.GetMethods(),操作方法同上。

更多精彩内容其他人还在看

ASP.NET 水晶报表打印功能实现代码

ASP.NET下的水晶报表打印,据我所知有以下几种办法可以打印
收藏 0 赞 0 分享

ASP.Net 图片存入数据库的实现代码

在很多时候,我们有这样的需求:把图片存入到数据库当中。在一些应用程序中,我们可能有一些敏感的资料,由于存储在文件系统(file system)中的东西,将很容易被某些用户盗取,所以这些数据不能存放在文件系统中。
收藏 0 赞 0 分享

让Silverlight 2.0动画动起来Making Silverlight 2.0 animation Start(不能运动原因)

Microsoft Expression Blend 2 制作动画个人感觉倒像3DMAX 可以自动捕捉关键帧
收藏 0 赞 0 分享

asp.net Reporting Service在Web Application中的应用

由于我们这个项目中使用微软的报表服务(Reporting Services)作为报表输出工具,本人也对它进行一点点研究,虽没有入木三分,但这点知识至少可以在大部分Reporting Service的场景中应用。
收藏 0 赞 0 分享

C# 文件上传 默认最大为4M的解决方法

.net中默只能上传小于4m的文件,大于4M将无法显示页面.那么如何设置来使imputfile能上传更大的文件呢
收藏 0 赞 0 分享

asp.net 购物车实现详细代码

asp.net 购物车实现详细代码
收藏 0 赞 0 分享

asp.net repeater实现批量删除时注册多选框id到客户端

repeater批量删除时注册多选框id到客户端的实现代码
收藏 0 赞 0 分享

asp.net aspnetpager分页统计时与实际不符的解决办法

最近分页方面根据实际需要修改了一些函数
收藏 0 赞 0 分享

iis 服务器应用程序不可用的解决方法

访问页面时提示 服务器应用程序不可用,大家可以按照下面的方法重新注册下,应该能好点
收藏 0 赞 0 分享

asp.net button 绑定多个参数

asp.net button 绑定多个参数的代码
收藏 0 赞 0 分享
查看更多