C# 利用反射動態調用類成員

來源:互聯網
上載者:User

使用反射動態調用類成員,需要Type類的一個方法:InvokeMember。對該方法的聲明如下:

public object InvokeMember(

string name,

BindingFlags invokeAttr,

Binder binder,

object target,

object[] args

);

參數

name

String,它包含要調用的建構函式、方法、屬性或欄位成員的名稱。

- 或 -

Null 字元串 (""),表示調用預設成員。

invokeAttr

一 個位屏蔽,由一個或多個指定搜尋執行方式的 BindingFlags 組成。訪問可以是 BindingFlags 之一,如 Public、NonPublic、Private、InvokeMethod 和 GetField 等。不需要指定尋找類型。如果省略尋找類型,則將應用 BindingFlags.Public | BindingFlags.Instance。

binder

一個 Binder 對象,該對象定義一組屬性並啟用綁定,而綁定可能涉及選擇重載方法、強制參數類型和通過反射調用成員。

- 或 -

若為空白引用(Visual Basic 中為 Nothing),則使用 DefaultBinder。

target

要在其上調用指定成員的 Object。

args

包含傳遞給要調用的成員的參數的數組。

傳回值

表示被調用成員的傳回值的 Object。

備忘:

下列 BindingFlags 篩選標誌可用於定義包含在搜尋中的成員:

為了擷取傳回值,必須指定 BindingFlags.Instance 或 BindingFlags.Static。

指定 BindingFlags.Public 可在搜尋中包含公用成員。

指定 BindingFlags.NonPublic 可在搜尋中包含非公用成員(即私人成員和受保護的成員)。

指定 BindingFlags.FlattenHierarchy 可包含階層上的靜態成員。

下列 BindingFlags 修飾符標誌可用於更改搜尋的執行方式:

BindingFlags.IgnoreCase,表示忽略 name 的大小寫。

BindingFlags.DeclaredOnly,僅搜尋 Type 上聲明的成員,而不搜尋被簡單繼承的成員。

可以使用下列 BindingFlags 調用標誌表示要對成員採取的操作:

CreateInstance,表示調用建構函式。忽略 name。對其他調用標誌無效。

InvokeMethod,表示調用方法,而不調用建構函式或類型初始值設定項。對 SetField 或 SetProperty 無效。

GetField,表示擷取欄位值。對 SetField 無效。

SetField,表示設定欄位值。對 GetField 無效。

GetProperty,表示擷取屬性。對 SetProperty 無效。

SetProperty 表示設定屬性。對 GetProperty 無效。

程式碼範例:

class Program
{
static void Main(string[] args)
{
object obj;

NewsEngine instance = (NewsEngine)System.Reflection.Assembly.Load("ReflectionData").CreateInstance("ReflectionData.NewsEngine");

System.Diagnostics.Debug.WriteLine(instance.GetItems());

//
//private string file = @"DataAccess.dll";

ReflectionEngine r = new ReflectionEngine(@"ReflectionData.dll");
r.DisplayModules();
r.DisplayTypes();
r.DisplayMethods();
r.InvokeStaticMethod();
r.InvokeMethod();

Console.Read();
}
}

public class ReflectionEngine
{
private string file;

public ReflectionEngine(string file)
{
this.file = file;
}

//顯示所有模組名
public void DisplayModules()
{
Console.WriteLine("display modules ...");
Assembly assembly = Assembly.LoadFrom(file);
Module[] modules = assembly.GetModules();
foreach (Module module in modules)
{
Console.WriteLine("module name:" + module.Name);
}
}
//顯示所有類型名
public void DisplayTypes()
{
Console.WriteLine("display types ...");
Assembly assembly = Assembly.LoadFrom(file);
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
Console.WriteLine("type name:" + type.FullName);
}
}
//先是一個類型中的所有方法名
public void DisplayMethods()
{
Console.WriteLine("display methods in TestReflection Type ...");
Assembly assembly = Assembly.LoadFrom(file);
Type type = assembly.GetType("ReflectionData.NewsEngine");
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
Console.WriteLine("method name:" + method.Name);
}
}
//調用一個類中的靜態方法
public void InvokeStaticMethod()
{
Console.WriteLine("Invoke static method ...");
Assembly assembly = Assembly.LoadFrom(file);
Type type = assembly.GetType("ReflectionData.NewsEngine");

type.InvokeMember("GetName", BindingFlags.InvokeMethod, null, null, new object[] { });
}
//調用一個類中的非靜態方法
public void InvokeMethod()
{
Console.WriteLine("Invoke Method ...");
Assembly assembly = Assembly.LoadFrom(file);
Type type = assembly.GetType("ReflectionData.NewsEngine");
Object obj = Activator.CreateInstance(type);

ReflectionData.NewsEngine tc = (ReflectionData.NewsEngine)obj;

Console.WriteLine(type.InvokeMember("GetItems", BindingFlags.InvokeMethod, null, tc, new object[] { }));
Console.WriteLine(type.InvokeMember("GetItemById", BindingFlags.InvokeMethod, null, tc, new object[] { 1 }));
}
}

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

測試代碼

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

namespace ReflectionData
{

public interface INewsEngine
{
string Name { get;}

string GetItems();

string GetItemById(int Id);
}

public class NewsEngine :INewsEngine
{
private string m_Name = "Common News Engine";

public string Name
{
get { return m_Name; }
}

public string GetItems()
{
return "news's method - GetItems().";
}

public string GetItemById(int Id)
{
return "news's method - GetItemById(" + Id + ").";
}

public static string GetName()
{
return "news's static method - GetName().";
}

}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.