C#反射(Reflection)对类的属性get或set值实现思路
作者:
可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性,接下来为大家介绍下对一个类别的属性进行set和get值,感兴趣的各位可以参考下哈
近段时间,有朋友叫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());
}
}
}