2010-10-13 184 views
4

我正在調用一個委託,我不是很瞭解它是如何工作的,我因爲它編譯錯誤(編譯器錯誤CS1660)。這是我有它的代碼:base.Invoke與代表

base.Invoke(delegate { 
      bool flag = (((this.layerPickPlaceProcess != null) && (this.robotComponent != null)) && ((((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Idle) || (((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Ready))) && ((((StateEnum) this.robotComponent.State) == StateEnum.Idle) || (((StateEnum) this.robotComponent.State) == StateEnum.Ready)); 
      this.cmdManualPlace.Enabled = flag; 
     }); 
+0

反射器是一個工具,將顯示反編譯程序集 - 該技術稱爲**反射**。 – Oded 2010-10-13 17:58:43

+0

我熟悉反射器,只是不與代表和反射也許沒有正確地吐出代碼? – mookie 2010-10-13 18:03:05

回答

6

添加(Action)

base.Invoke((Action)delegate { 
      bool flag = (((this.layerPickPlaceProcess != null) && (this.robotComponent != null)) && ((((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Idle) || (((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Ready))) && ((((StateEnum) this.robotComponent.State) == StateEnum.Idle) || (((StateEnum) this.robotComponent.State) == StateEnum.Ready)); 
      this.cmdManualPlace.Enabled = flag; 
     }); 

這是因爲調用接受Delegate這不是委託據類型作爲C#編譯器是關心(原文如此!) 。委託類型應該定義一個呼叫簽名,而Delegate不是,它只是一個共同的祖先。表達式delegate { ... }有類型...嘗試猜... 匿名代理(如果它是一種方法,它將是方法組)。他們也不是委託類型!但它們可以隱式轉換爲具有匹配簽名的委託類型。代表類型可以隱式轉換爲Delegate

Action是:public delegate void Action();

簡單地說,鏈:

  • Anonymous methodDelegate:如果簽名匹配
  • ActionDelegate隱式轉換:轉換不存在
  • Anonymous methodAction隱式轉換(Action是01的後裔)

它們合併:

  • Anonymous methodActionDelegate:它的作品!
+0

我需要Action <>的至少一個參數。我敢嘗試行動? – mookie 2010-10-13 18:02:30

+0

@mookie有委託類型'Action'沒有參數 – Andrey 2010-10-13 18:05:20

+0

目前爲止還沒有回答。 – Timwi 2010-10-13 18:15:00

2

試試這個:

// MethodInvoker is also acceptable. 
Action action = delegate 
     { 
      bool flag = (((this.layerPickPlaceProcess != null) && (this.robotComponent != null)) && ((((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Idle) || (((StateEnum) this.layerPickPlaceProcess.State) == StateEnum.Ready))) && ((((StateEnum) this.robotComponent.State) == StateEnum.Idle) || (((StateEnum) this.robotComponent.State) == StateEnum.Ready)); 
      this.cmdManualPlace.Enabled = flag; 
     }; 

base.Invoke(action); 

你必須告訴編譯器一個特定委託型使用;可能有任何數量的委託類型與匿名方法兼容。

您可能會發現這MSDN page有幫助,雖然它沒有提到爲什麼C#編譯器不認爲System.Delegate是委託類型,這是真正的問題。

+0

沒有錯,但很高興提到兩種語法之一,它們允許在沒有臨時變量的情況下將其寫入一個語句中。 – Timwi 2010-10-13 18:14:20