[英]Call a method passed as parameter on an object passed as parameter
我有一個類定義了幾個具有相同簽名的函數
public class MyClass
{
public string MyParam1() ...
public string MyParam2() ...
...
}
從另一個類,我想在作為參數傳遞的對象上調用作為參數傳遞的方法
void MyFunction(MyClass anObject, Func<string> aMethod)
{
string val = ??? // Here call aMethod on anObject
}
我很確定可以使用反射來做到這一點,但是有沒有困難的方法呢?
實際上,我有一組對象,而不是單個對象,這就是為什么我不能直接調用該對象的方法的原因。
如果將實例方法作為函數傳遞,則該方法已綁定到該實例 ,因此在這種情況下 , anObject
無效。
此代碼已在this
運行:
MyFunction(null, this.DoSomething);
val
始終是調用者上下文中this.DoSomething
的結果:
string val = aMethod();
您可以做的是創建一個靜態方法,該方法具有anObject
參數,而不是傳遞實例方法。 這樣,您的靜態方法就可以執行實例特定的任務。
public string MyParam2(MyClass instance) { }
void MyFunction(MyClass anObject, Func<MyClass, string> aMethod)
{
string val = aMethod(anObject);
}
您無需擔心anObject
因為aMethod
已綁定到實例 。 委托的定義是對方法實例的引用 。
因此,以下內容就足夠了:
void MyFunction(Func<string> aMethod)
{
string val = aMethod();
}
如果您真的想在對象上調用給定的方法,請不要使用Func
而是傳入對象和方法的名稱:
class Test
{
public static void SayHello()
{
Console.WriteLine("Hello");
}
}
void Main()
{
var t = new Test();
var methodInfo = t.GetType().GetMethod("SayHello");
methodInfo.Invoke(t, null);
}
執行后,將打印
Hello
因為它將在Test
實例t
上調用SayHello
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.