2011-12-14 28 views
0

我有一個MethodInfo對象,它定義了我想要調用的方法。如何調用MethodInfo?

除了我需要MethodInfo來自的object

僞代碼:

void CallMethod(MethodInfo m) 
{ 
    Object o = Activator.CreateInstance(m.ClassType); 
    o.GetType().InvokeMember(m.Name, BindingFlags.InvokeMethod, null, o, null); 
} 

除了我不知道如何獲取MethodInfo屬於類的type

我怎麼能叫MethodInfo

回答

2

這將創建一個從你的MethodInfo是類型的對象,將調用它爲您新的對象。

void CallMethod(MethodInfo m) 
{ 
    Object o = Activator.CreateInstance(m.ReflectedType); 
    m.Invoke(o, null); 
} 
0

可以確定哪個通過訪問MethodInfo對象的DeclaringType屬性定義該方法的類型。

5

MethodInfo知道該方法調用的目標 - 的MethodInfo有效屬於類型,而不是一個特定對象。

你必須要在其上調用方法的目標類型的實例。你可以很容易找到足夠使用MethodInfo.DeclaringType(從MemberInfo.DeclaringType繼承)的類型,但你可能沒有一個實例在這一點......

正如裏德指出,MemberInfo.ReflectedType可能比​​更合適,這取決於你怎麼樣計劃使用它。

你還沒有解釋你正在做什麼的任何事情,但如果你的設計的其他部分可以適當地更改,那麼採用Action代表而不是MethodInfo可能更合適。

+1

您不妨提一下,如果它是靜態的,則不需要實例。 – x0n 2011-12-14 20:55:51

+0

另外 - 值得一提的是`ReflectedType`屬性*可能更合適,因爲`DeclaringType`可能是一個抽象類... – 2011-12-14 20:56:59

+0

@ReedCopsey:會的。 – 2011-12-14 21:16:27

0

我可能誤解了這個問題,但它聽起來像是在代理之後而不是MethodInfo。

void Main() 
{ 
    Object myObject = new ArrayList(); 
    MethodInfo methodInfo = myObject.GetType().GetMethod("Clear"); 
    Delegate method = Delegate.CreateDelegate(typeof(Action), myObject, methodInfo, true); 
    CallMethod(method); 
} 

void CallMethod(Delegate method) 
{ 
    method.DynamicInvoke(); 
} 

有明確收購這種情況下(method = new Action(myObject.Clear))委託一個更簡單的方法,但我會在你需要使用一個MethodInfo對象的問題。