回調

2012-09-18 32 views
3

以下是我在C#代碼...回調

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     TestPointer test = new TestPointer(); 
     test.function1(function2); // Error here: The name 'function2' does not exist in  current context 
    } 
} 

class TestPointer 
{ 
    private delegate void fPointer(); // point to every functions that it has void as return value and with no input parameter 
    public void function1(fPointer ftr) 
    { 
     fPointer point = new fPointer(ftr); 
     point(); 
    } 

    public void function2() 
    { 
     Console.WriteLine("Bla"); 
    } 
} 

我如何通過傳遞函數refernce在主函數中調用回調函數?... 我是新來的C#

+0

你到底想達到什麼目的? (順便說一句,這看起來像_C#_,而不是C++)。 – Oded

回答

3

test.function1(test.function2)應該這樣做。

你還需要的

public delegate void fPointer(); 

代替

private delegate void fPointer(); 
+0

不工作... –

+0

啊,你必須把你的委託標記爲'public',以便在課堂外使用。它現在編譯和運行對我來說很好。 – Rawling

+0

正在工作:) ..thnx更正 –

0

你需要讓function2static或通過text.function2

+0

仍然不能正常工作 –

+0

如果你使'function2'爲靜態,你需要通過'TestPointer.function2'。如果不是,你需要通過'test.function2',而不是'text.funxtion2'。 – Rawling

1

你可以用行動做到這一點:

class Program 
    { 
     static void Main(string[] args) 
     { 
      TestPointer test = new TestPointer(); 
      test.function1(() => test.function2()); // Error here: The name 'function2' does not exist in  current context 

      Console.ReadLine(); 
     } 
    } 

    class TestPointer 
    { 
     private delegate void fPointer(); // point to every functions that it has void as return value and with no input parameter 
     public void function1(Action ftr) 
     { 
      ftr(); 
     } 

     public void function2() 
     { 
      Console.WriteLine("Bla"); 
     } 
    } 
1

有2個問題,你的代碼:

TestPointer test = new TestPointer(); 
    test.function1(function2); 

這裏,不存在所謂的function2範圍變量。什麼,你想做的事就是這樣稱呼它:

test.function1(test.function2); 

test.function2事實上是method group,在這種情況下會被編譯器轉換爲委託。對下一個問題:

private delegate void fPointer(); 
public void function1(fPointer ftr) 

您聲明委託爲私人。它應該是公開的。 A delegate is a special kind of type,但它仍然是一個類型(您可以聲明'em'的變量,這正是您將參數聲明爲function1時所做的操作)。當聲明爲私人類型時,類別TestPointer以外的類別不可見,因此不能用作公共方法的參數。

最後,不是一個真正的錯誤,但你所說的委託方式可以簡化爲:

ftr(); 

因此,這裏是你的更正後的代碼:

using System; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     TestPointer test = new TestPointer(); 
     test.function1(test.function2); 
    } 
} 

class TestPointer 
{ 
    public delegate void fPointer(); 
    public void function1(fPointer ftr) 
    { 
     ftr(); 
    } 

    public void function2() 
    { 
     Console.WriteLine("Bla"); 
    } 
}