1. 程式人生 > >C#反射(Reflection)對類的屬性get或set值

C#反射(Reflection)對類的屬性get或set值

近段時間,有朋友叫Insus.NET瞭解一下反射(Reflection)方面的知識,反射提供了封裝程式集、模組和型別的物件(Type型別)。可以使用反射動態建立型別的例項,將型別繫結到現有物件,或從現有物件獲取型別並呼叫其方法或訪問其欄位和屬性。如果程式碼中使用了屬性,可以利用反射對它們進行訪問。

下面的例子,是Insus.NET是練習對一個類別的屬性進行set和get值。

首先寫一個類,再寫一個可讀寫的屬性:

View Code
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:

View Code
using Insus.NET;
using System.Reflection;


讀寫屬性:

View Code
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());
        }
    }
}