[英]C# Pass type (class) method like parameter
我想將類型(類)中的方法像參數一樣傳遞給另一個方法,我不知道該怎么做。
class Program
{
static void Main(string[] args)
{
MyMethod(Foo.MethodA);
MyMethod(Foo.MethodB);
}
public void MyMethod(???)
{
}
}
public class Foo
{
public void MethodA()
{
}
public int MethodB(int val)
{
return val;
}
}
我只想這樣做
MyMethod(Foo.MethodA);
我不想從 object 傳遞方法,而只是從類型(類)
我不確定您要做什么,但是您可以將方法概括為Delegate
。
static void Main(string[] args)
{
MyMethod(new Action(Foo.MethodA));
MyMethod(new Func<int,int>(Foo.MethodB));
}
public static void MyMethod(Delegate del)
{
// Example code
var methodInfo = del.Method;
var methodName = methodInfo.Name;
}
您仍然需要將方法包裝在一些委托中,例如Action
或Func<>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.