2014-07-06 45 views
0

當我嘗試向Dictionary <string, Delegate>添加方法/函數時,出現編譯錯誤。你能告訴我如何將我的方法geometryContentParser()添加到字典中嗎?也許我需要將字典值類型更改爲Event而不是Delegate添加方法到代表字典

編譯錯誤:

Cannot convert method group 'geometryContentParser' to non-delegate type 'System.Delegate'. Consider using parentheses to invoke the method

繼承人我簡單的代碼:

public class FileParser 
{ 
    private Dictionary<string, Delegate> customParsingCallbacks = new Dictionary<string, Delegate>(); 

    public FileParser() 
    { 
     customParsingCallbacks["points"] = geometryContentParser; // compile error: "Cannot convert method group `geometryContentParser' to non-delegate type `System.Delegate'. Consider using parentheses to invoke the method" 
    } 

    private bool geometryContentParser(string formattedLine) { 
     // Post: Returns True if this custom content parser is still running (needs to look at the next line) else false for completion 

     if (formattedLine.Contains("}")) { 
      return false; 
     } 

     return true; 
    } 
} 

而且這是正確的調用方法?

customParsingCallbacks["points"](""); 
// OR 
customParsingCallbacks["points"].DynamicInvoke(""); 
+0

只要將它轉換爲'Delegate'。沒有默認轉換。 – siride

+0

但實際上,你應該定義你的委託類型來接受一組特定的參數並返回一個特定的值,所以你可以使用某種版本的'Func <>'或'Action <>'而不是使用最通用的類​​型'Delegate')。將傳遞給這些方法的參數是什麼?返回值會做什麼? – siride

+0

對於第二部分(調用vs DynamicInvoke),請參閱此問題:http://stackoverflow.com/questions/12858340/difference-between-invoke-and-dynamicinvoke – qbik

回答

2

除了使用代表使用Func鍵,見下面的代碼

public class FileParser 
{ 
    private Dictionary<string, Func<string, bool>> customParsingCallbacks = new Dictionary<string, Func<string, bool>>(); 

    public FileParser() 
    { 
     customParsingCallbacks["points"] = new Func<string, bool>((s) => { 
               return geometryContentParser(s); 
                    }); 
    } 

    private bool geometryContentParser(string formattedLine) 
    { 
     // Post: Returns True if this custom content parser is still running (needs to look at the next line) else false for completion 

     if (formattedLine.Contains("}")) 
     { 
      return false; 
     } 

     return true; 
    } 
} 

打電話,做這樣的

bool result = customParsingCallbacks["points"]("somestring");