可以說我有一個方法C#通過變量引用方法?
public static void Blah(object MyMethod) { // i dont know what to replace object with
MyMethod; // or however you would use the variable
}
所以基本上我需要能夠通過可變
可以說我有一個方法C#通過變量引用方法?
public static void Blah(object MyMethod) { // i dont know what to replace object with
MyMethod; // or however you would use the variable
}
所以基本上我需要能夠通過可變
您正在尋找a delegate引用的方法。
public delegate void SomeMethodDelegate();
public void DoSomething()
{
// Do something special
}
public void UseDoSomething(SomeMethodDelegate d)
{
d();
}
用法:
UseDoSomething(DoSomething);
或者使用lambda語法(如DoSomething
是一個Hello World):
UseDoSomething(() => Console.WriteLine("Hello World"));
public void UseDoSomething(Action d)
如果你需要從你的委託返回值(就像我的例如int
),你可以使用:
public void UseDoSomething2(Func<int> d)
.Net框架有一堆內置的委託類型,這使得這更容易。所以,如果MyMethod
需要string
參數,你可以這樣做:
public static void Blah(Action<string> MyMethod) {
MyMethod;
}
,如果它需要兩個int
S和返回long
你會做:
public static void Blah(Func<int, int, long> MyMethod) {
MyMethod;
}
還有的Action<>
版本和Func<>
與不同數量您可以根據需要指定類型參數。
[傳遞方法作爲參數使用C#]的可能重複(http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) – 2012-03-12 01:35:44