2013-03-28 33 views
1

我想學習C#的代表。編譯此位代碼時,我在主題行中收到此錯誤消息。不能類型「詮釋」隱式轉換爲「Foo.Bar.Delegates.Program.ParseIntDelegate」

不能類型「詮釋」隱式轉換爲「Foo.Bar.Delegates.Program.ParseIntDelegate」

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

namespace Foo.Bar.Delegates 
{ 
    class Program 
    { 
     private delegate int ParseIntDelegate(); 

     private static int Parse(string x) 
     { 
      return int.Parse(x); 
     } 

     static void Main() 
     { 
      string x = "40"; 
      int y = Parse(x); //The method I want to point the delegate to 

      ParseIntDelegate firstParseIntMethod = Parse(x); 

      //generates complier error: cannot implicity convert type int 
      //to 'Foo.Bar.Delegates.Program.ParseIntDelegate' 

      ParseIntDelegate secondParseIntMethod = int.Parse(x); //Same error 

      Console.WriteLine("Integer is {0}", firstParseIntMethod()); 
     } 
    } 
} 

所以我堅持,直到我能理解它是什麼,我做錯了。如果有人能幫我解決這個問題,我會非常感激。

回答

4

首先,您的委託類型應該是:

private delegate int ParseIntDelegate(string str); 

委託類型應與你要轉換的方法的簽名。在這種情況下Parse接受一個string參數並返回一個int

由於您Parse方法有一個兼容的特徵,你可以直接從它創建一個新的委託實例:

ParseIntDelegate firstParseIntMethod = Parse; 

然後你就可以調用它像一個正常的方法應用:

Console.WriteLine("Integer is {0}", firstParseIntMethod(x)); 
0

有一些東西,跳出來對我:

在Main()中,您有

ParseIntDelegate firstParseIntMethod = Parse(x); 

這試圖存儲解析(X)轉換成firstParseIntMethod的結果。你調用解析這裏,不是指它。

您可以通過刪除參數解決這個問題:

ParseIntDelegate firstParseIntMethod = Parse ; 

現在你將有一個不同的錯誤,抱怨解析的簽名。

private delegate int ParseIntDelegate(); 

private static int Parse(string x) 

解析不能'擬合'到ParseIntDelegate中,因爲它需要一個字符串參數。您可以更改ParseIntDelegate以採用字符串來解決問題。

+0

是,請先參閱,然後調用並獲得相匹配的簽名。多謝你們。 – birdinacage

+0

很樂意幫忙 - 如果這是對你有用,你可能標誌着李的回答是解決你的問題。 –

+0

我如何評價李? – birdinacage

相關問題