2009-08-25 65 views
2

我想知道是否有可能(以及什麼語法)將對象的方法發送到函數。是否可以將對象的方法發送給函數?

例子:

Object "myObject" has two methods "method1" and "method2" 

我想有沿線的一個功能:

public bool myFunc(var methodOnObject) 
{ 
    [code here] 
    var returnVal = [run methodOnObject here] 
    [code here] 
    return returnVal; 
} 

因此,在其他功能我可以做類似

public void overallFunction() 
{ 
    var myObject = new ObjectItem(); 
    var method1Success = myFunc(myObject.method1); 
    var method2Success = myFunc(myObject.method2); 
} 
+2

Delgates應該解決您的問題 – 2009-08-25 13:48:35

回答

3

真的需要明確的代表嗎?也許這種方法會幫助你:

private class MyObject 
{ 
    public bool Method1() { return true; } // Your own logic here 
    public bool Method2() { return false; } // Your own logic here 
} 

private static bool MyFunction(Func<bool> methodOnObject) 
{ 
    bool returnValue = methodOnObject(); 
    return returnValue; 
}  

private static void OverallFunction() 
{ 
    MyObject myObject = new MyObject(); 

    bool method1Success = MyFunction(myObject.Method1); 
    bool method2Success = MyFunction(myObject.Method2); 
} 
+2

不知道這是否是一個錯字...'Func <...>'非常**是**委託。 – 2009-08-25 14:18:27

+0

抱歉刪除我的評論,這是關於「是否真的需要代表?」並使用Func作爲代表... – 2009-08-25 14:23:37

+0

這很好,謝謝。我直接接受了這個答案,因爲它直接使用了我的示例。 – ChrisHDog 2009-08-25 22:58:48

2

是,使用代表..

這裏是一個例子..

delegate string myDel(int s); 
public class Program 
{ 
    static string Func(myDel f) 
    { 
     return f(2); 
    } 

    public static void Main() 
    { 
     Test obj = new Test(); 
     myDel d = obj.func; 
     Console.WriteLine(Func(d)); 
    } 
} 
class Test 
{ 
    public string func(int s) 
    { 
     return s.ToString(); 
    } 
} 
+0

提供了一個例子可能會給你相當長的一段了,票... – 2009-08-25 13:49:53

8

是的,你需要使用一個委託。委託與C/C++中的函數指針相當類似。

您首先需要聲明委託人的簽名。說我有這樣的功能:

private int DoSomething(string data) 
{ 
    return -1; 
} 

的委託聲明將是...

public delegate int MyDelegate(string data); 

然後,您可以用這種方式宣告myFunc的..

public bool myFunc(MyDelegate methodOnObject) 
{ 
    [code here] 
    int returnValue = methodOnObject("foo"); 
    [code here] 
    return returnValue; 
} 

然後,您可以調用它有兩種方法:

myFunc(new MyDelegate(DoSomething)); 

或者,在C#3.0及更高版本,可以使用的速記......

myFunc(DoSomething); 

(它只是包含在該委託自動默認的構造函數提供的功能。這些呼叫在功能上是相同的)。

如果你不關心實際創建一個委託或簡單表達式的實際功能的實現,下面的工作在C#3.0,以及:

public bool myFunc(Func<string, int> expr) 
{ 
    [code here] 
    int returnValue = methodOnObject("foo"); 
    [code here] 
    return returnValue; 
} 

然後可稱爲像這樣:

myFunc(s => return -1); 
+1

C#3.5也可以讓你避免宣告自己的委託類型,你可以執行'Func ',它表示與你的'MyDelegate'類型相同的簽名。 – 2009-08-25 14:03:26

+1

@Simon:在某些情況下,是的,有一些內置的委託類型,3.5增加了幾個可能有用的作爲LINQ支持包的一部分。這就是說,能夠聲明委託是IMO,任何.NET開發人員都應該能夠做到的事情。 – 2009-08-25 15:20:20

+0

偉大的答案,感謝所有的信息和細節。投了票,但用其他作爲官方答案,因爲它直接使用我的例子。有時候希望可以有2個被接受的答案,因爲結合你的兩個答案給出了任何人可能想要的這個問題的所有細節。再次感謝! – ChrisHDog 2009-08-25 23:00:33

相關問題