.net反射

來源:互聯網
上載者:User

標籤:

一、  反射就是動態發現類型資訊的能力。它協助程式設計人員在程式運行時利用一些資訊去動態地使用類型,這些資訊在設計時是未知的,這種能力類型於後期綁定。反射還支援的更進階的行為,能在運行時動態建立新類型,並且對這些新類型的操作進行調用。

 

二、一些在反射中經常使用的類

Assembly類

      Assembly類是可重用、無版本衝突並且可自我描述的公用語言運行庫應用程式構造塊。可以使用Assembly.Load和Assembly.LoadFrom方法動態地載入程式集。

Type類

      反射的中心是System.Type類。System.Type類是一個抽象類別,代表公用類型系統中的一種類型。這個類使您能夠查詢類型名、類型中包含的模組和名稱空間、以及該類型是一個數實值型別還是一個參考型別。
System.Type類使您能夠查詢幾乎所有與類型相關的屬性,包括類型訪問限定符、類型是否、類型的COM屬性等等。

Activator類

      Activator類支援動態建立.NET程式集和COM對象。可以通過CreateComInstanceFrom、CreateInstance、CreateInstanceFrom、GetObject四個靜態方法載入COM對象或者程式集,並能建立指定類型的執行個體。

Binder類

      Binder類是一個用於執行類型轉換的綁定器,Type對象的InvokeMember方法接受Binder對象,這個對象描述了如何將傳遞給InvokeMember的參數轉換成方法實際需要的類型。
      Binder類是一個抽象類別,要建立綁定器,需要重寫方法BindToMethod、BindToField、SelectMehtod、SelectProperty和ChangeType。

DefaultMemberAttribute類

    DefaultMemberAttribute類用於類型並帶有一個指明預設成員名稱的字串參數。能夠通過InvokeMember調用預設成員,而不需要傳遞調用成員的名稱。當需要綁定器但不需要特別的綁定行為時就可以使用它。

 

三、還有一些對元素類型資訊描述的類,ConstrutorInfo(建構函式)、MethodInfo(方法)、FieldInfo(欄位)、PropertyInfo(屬性)、EventInfo(事件)、MemberInfo(成員)、ParameterInfo(參數)。如果查詢得到了具有任何類型資訊的執行個體,就可以獲得該類型中任意元素的類型資訊,當然出於安全原因,不保證會得到程式集中的任何資訊。

 

四、樣本

類定義

 

代碼

using System;
using System.Collections.Generic;
using System.Text;

namespace ReflectionSample
{
/**//**//**////
/// 說明:一個簡單的類
/// 文野
/// 聯絡:stwyhm.cnblog.com
///
public class ClassSample
{
// 預設構造
public ClassSample()
{
this.name = "您調用了預設構造建立了一個類執行個體。";
}

// 帶參構造
public ClassSample(string name)
{
this.name = name;
}

// 欄位
public string name;

public string Field;

// 屬性
private string property;
public string Property
{
set { this.property = value; }
get { return property; }
}

// public方法
public string PublicClassMethod()
{
return string.Format("您反射了一個Public方法");
}

// private方法
private string PrivateClassMethod()
{
return string.Format("您反射了一個Private方法");
}

// static方法
public static string StaticMethod()
{
return "您反射了一個Static方法";
}

// 帶參方法
public string ParameterMethod(string para)
{
return para;
}

public event EventHandler eventHandler;

public void DoEvent()
{
eventHandler(null,EventArgs.Empty);
}
}
}

 

反射樣本

 

代碼

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Reflection;
using ReflectionSample;

/**//**//**////
/// 說明:一個簡單的使用反射樣本
/// 文野
/// 聯絡:stwyhm.cnblog.com
///
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string path = Server.MapPath(Request.Path);
string filePath = path.Substring(0, path.LastIndexOf(‘‘\\‘‘)) + @"\bin\ReflectionSample.dll";
// 擷取程式集
Assembly classSampleAssembly = Assembly.LoadFrom(filePath);

// 從程式集中擷取指定物件類型
Type classSampleType = classSampleAssembly.GetType("ReflectionSample.ClassSample");

使用Activator建立一個執行個體使用Activator建立一個執行個體#region 使用Activator建立一個執行個體

// 通過物件類型建立對象執行個體
ClassSample s1 = Activator.CreateInstance(classSampleType) as ClassSample;

Response.Write(s1.name + "(使用Activator建立一個執行個體)");

#endregion

動態調用建構函式動態調用建構函式#region 動態調用建構函式

// 調用無參構造
ConstructorInfo studentConstructor1 = classSampleType.GetConstructor(new Type[] { });
ClassSample s2 = studentConstructor1.Invoke(new object[] { }) as ClassSample;
Response.Write(s2.name + "");

// 調用有參構造
ConstructorInfo studentConstructor2 = classSampleType.GetConstructor(new Type[] { typeof(string) });
ClassSample s3 = studentConstructor2.Invoke(new object[] { "您調用了有參構造建立了一個類執行個體。" }) as ClassSample;
Response.Write(s3.name + "");

#endregion

反射方法反射方法#region 反射方法

// 調用非靜態方法
string returnValue1 = classSampleType.InvokeMember("PublicClassMethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, s1, new object[] { }) as string;
Response.Write(returnValue1 + "");

// 調用靜態方法
string returnValue2 = classSampleType.InvokeMember("StaticMethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, s1, new object[] { }) as string;
Response.Write(returnValue2 + "");

// 調用私人方法
string returnValue3 = classSampleType.InvokeMember("PrivateClassMethod", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, s1, new object[] { }) as string;
Response.Write(returnValue3 + "");

#endregion

//反射參數反射參數#region 反射參數

MethodInfo parameterMethod = classSampleType.GetMethod("ParameterMethod");
ParameterInfo[] paras = parameterMethod.GetParameters();
for (int i = 0; i ", new object[] { paras[i].Name, paras[i].ParameterType.ToString(), paras[i].IsOptional.ToString(), paras[i].Position.ToString(), paras[i].DefaultValue.ToString() }));

#endregion

//反射屬性反射屬性#region 反射屬性

classSampleType.InvokeMember("Property", BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance, null, s1, new object[] { "您反射了一個屬性" });
string returnValue4 = classSampleType.InvokeMember("Property", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, s1, new object[] { }) as string;
Response.Write(returnValue4 + "");

#endregion

//反射欄位反射欄位#region 反射欄位

classSampleType.InvokeMember("Field", BindingFlags.SetField | BindingFlags.Public | BindingFlags.Instance, null, s1, new object[] { "您反射了一個欄位" });
string returnValue5 = classSampleType.InvokeMember("Field", BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance, null, s1, new object[] { }) as string;
Response.Write(returnValue5 + "");

#endregion
}
}

 

 

五、.net反射機制

 

.net反射機製為建立對象和調用其他方法提供了替代方案。比如為了提高代碼的靈活性。但是問題確是我們要編寫更多的代碼來實現。
使用反射機制是有一些缺點的。其最大的缺點就是編譯器無法對對象進行類型檢查,此時IDE的智能感知將無能為力。但是他的真正優勢又在什麼地方呢?它提供了一種手段,將指定具體類延遲到了運行時刻。
使用反射機制調用方法的四步曲:
1 載入程式集
2 擷取類的類型
3 建立該類的執行個體
4 調用該執行個體的方法
System.Reflection.Assembly類中有兩個靜態方法Assembly.Load(string assemblyName)和Assembly.LoadFrom(string fileName)來把程式集載入到應用程式序域中。
PS:在。NET中當一個對象被建立時,幕後到底發生了什嗎?當我們運行某一個應用程式時,.NET CLR會首先建立一個應用程式定義域來容納這個應用程式,接著將應該引用的程式集載入到應用程式定義域中。其中MSCorLib.dll是一個程式集,它包含了很多系統命名空間及其子命名空間中的類:System;System.Text,System.IO等。該程式集合中。然後CLR載入正在啟動並執行應用程式所屬的程式集。
DEMO:

(1)namespace ClassLibrarySport

{

    public abstract class Sport

    {

        protected string name;

        public abstract string GetName();

        public abstract string GetDuration();

    }

}

= = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = =

(2)namespace ClassLibrarySomeSports//該項目添加了對(1)的引用

{

    public class Football : ClassLibrarySport.Sport

    {

        public Football()

        {

            name = "Football";

        }

        public override string GetName()

        {

            return name;

        }

        public override string GetDuration()

        {

            return "four 15 minute quarters";

        }

    }

}

= = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = =

(3)namespace ConsoleAssemblyTest//該項目添加了對(1)的引用

{

    class Program

    {

        static void Main(string[] args)

        {

            Assembly assembly = Assembly.LoadFrom(@"E:\ClassLibrarySomeSports\

bin\Debug\ClassLibrarySomeSports.dll");

            Type[] types = assembly.GetTypes();

 

            Console.WriteLine("Get Type From ClassLibrarySomeSports.dll:");

            for (int i = 0; i < types.Length; i++)

            {

                Console.WriteLine(types[i].Name);

            }

 

            //使用GetConstructor()方法擷取對應類型的構造器,從而構造出該類型的對象

            Console.WriteLine("Use Method GetConstructor():");

            ConstructorInfo ci = types[0].GetConstructor(new Type[0]);

            ClassLibrarySport.Sport sport = (ClassLibrarySport.Sport)ci.Invoke(new object[0]);

            Console.WriteLine(sport.GetName() + " has " + sport.GetDuration());

 

            //使用Activator.CreateInstance()方法構造出該類型的對象

//使用assembly.CreateInstance()返回為null,??

            Console.WriteLine("Use Method CreateInstance():");

            ClassLibrarySport.Sport sport1 = (ClassLibrarySport.Sport)

Activator.CreateInstance(types[0]);

            Console.WriteLine(sport1.GetName() + " has " + sport1.GetDuration());

 

            //反射指定類型中的名稱為“GetDuration”的方法,通過Invoke()方法執行該方法

            object objSport = Activator.CreateInstance(types[0]);

            MethodInfo method = types[0].GetMethod("GetDuration");

            object o = method.Invoke(objSport, new object[0]);

            Console.WriteLine(o as string);

 

            Console.Read();

        }

    }

}

= = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = =

Output:

Get Type From ClassLibrarySomeSports.dll:

Football

Use Method GetConstructor():

Football has four 15 minute quarters

Use Method CreateInstance():

Football has four 15 minute quarters

four 15 minute quarters

.net反射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.