C#反射(Reflection)对类的属性get或set值实现思路
程序员文章站
2024-03-02 19:10:22
近段时间,有朋友叫insus了解一下反射(reflection)方面的知识,反射提供了封装程序集、模块和类型的对象(type类型)。可以使用反射动态创建类型的实例,将类型绑...
近段时间,有朋友叫insus了解一下反射(reflection)方面的知识,反射提供了封装程序集、模块和类型的对象(type类型)。可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。如果代码中使用了属性,可以利用反射对它们进行访问。
下面的例子,是insus练习对一个类别的属性进行set和get值。
首先写一个类,再写一个可读写的属性:
using system;
using system.collections.generic;
using system.linq;
using system.web;
/// <summary>
/// summary description for member
/// </summary>
namespace insus.net
{
public class member
{
private string _name;
public string name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public member()
{
//
// todo: add constructor logic here
//
}
}
}
insus.net一向是写asp.net程序,练习也是在站点进行。
创建一个网页,引用两个namespace:
using insus.net;
using system.reflection;
读写属性:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using insus.net;
using system.reflection;
public partial class _default : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
//实例化类
member objmember = new member();
//对属性set值
propertyinfo pi = objmember.gettype().getproperty("name", bindingflags.public | bindingflags.instance);
if (null != pi && pi.canwrite)
{
pi.setvalue(objmember, "insus.net", null);
}
//对属性get值
propertyinfo pii = objmember.gettype().getproperty("name", bindingflags.public | bindingflags.instance);
if (null != pii && pi.canread)
{
object obj_name = pii.getvalue(objmember, null);
response.write(obj_name.tostring());
}
}
}
下面的例子,是insus练习对一个类别的属性进行set和get值。
首先写一个类,再写一个可读写的属性:
复制代码 代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.web;
/// <summary>
/// summary description for member
/// </summary>
namespace insus.net
{
public class member
{
private string _name;
public string name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public member()
{
//
// todo: add constructor logic here
//
}
}
}
insus.net一向是写asp.net程序,练习也是在站点进行。
创建一个网页,引用两个namespace:
复制代码 代码如下:
using insus.net;
using system.reflection;
读写属性:
复制代码 代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using insus.net;
using system.reflection;
public partial class _default : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
//实例化类
member objmember = new member();
//对属性set值
propertyinfo pi = objmember.gettype().getproperty("name", bindingflags.public | bindingflags.instance);
if (null != pi && pi.canwrite)
{
pi.setvalue(objmember, "insus.net", null);
}
//对属性get值
propertyinfo pii = objmember.gettype().getproperty("name", bindingflags.public | bindingflags.instance);
if (null != pii && pi.canread)
{
object obj_name = pii.getvalue(objmember, null);
response.write(obj_name.tostring());
}
}
}