栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

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

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

要想对一个类型实例的属性或字段进行动态赋值或取值,首先得得到这个实例或类型的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) + "
");
}
//单独取值
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(),操作方法同上。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/58631.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号