2011-06-04 53 views
2
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 
using System.IO; 
using System.Collections; 
using System.ComponentModel; 

namespace ConsoleApplication1 
{ 
    class BreakingChange 
    { 
     delegate void SampleDelegate(string x); 

     public void CandidateAction(string x) 
     { 
      Console.WriteLine("Snippet.CandidateAction"); 
     } 

     public class Derived : BreakingChange 
     { 
      public void CandidateAction(object o) 
      { 
       Console.WriteLine("Derived.CandidateAction"); 
      } 
     } 

     static void Main() 
     { 
      Derived x = new Derived(); 
      SampleDelegate factory = new SampleDelegate(x.CandidateAction); 
      factory("test"); 
     } 
    } 
} 

\ Program.cs的(32,38):警告CS1707:委託 'ConsoleApplication1.BreakingChange.SampleDelegate' 結合到 'ConsoleApplication1.BreakingChange.Derived.CandidateAction(對象)' 而不是「ConsoleApplication1.BreakingChange.CandidateAction (相關位置) \的Program.cs(16,21):由於新的語言規則 \的Program.cs(23,25)(串)」(相關位置)如何糾正警告CS1707?

問題: 我知道是什麼原因引發了這個警告,並知道背後的原因。但是,我不知道 最好的修復方法是什麼?

1>重新定義函數(即)改變功能的簽名

2>,我們可以顯式調用BreakingChange.CandidateAction以下行?

SampleDelegate factory = new SampleDelegate(x.CandidateAction); 

回答

3

那麼,有多種方法可以「修復」這取決於你想要什麼,可以做什麼。

就我個人而言,我會將另一個重載添加到帶有字符串的Derived,因爲您也會遇到與非委託調用相同的問題。

public class Derived : BreakingChange 
{ 
    public new void CandidateAction(string x) 
    { 
     base.CandidateAction(x); 
    } 

    public void CandidateAction(object o) 
    { 
     Console.WriteLine("Derived.CandidateAction"); 
    } 
} 

或者,因爲你知道你想要的基類的方法,你可以投的參考x

new SampleDelegate(((BreakingChange)x).CandidateAction) 
+0

正要張貼,去年(CAST)的例子;好的答案 – 2011-06-04 21:54:33

+0

我想通過引用C#規範的確切部分來概括出爲什麼警告首先出現,並且我認爲它在7.3節(http://msdn.microsoft.com /en-us/library/aa691331(VS.71).aspx),但我不善於查看它是否真的有用。 OP表示他知道原因,但對於未來的訪問者來說,最好有明確的原因。 – 2011-06-04 22:14:31

+0

唉,這是一個非常舊的鏈接,讓我檢查更新的一個,也許這是更清晰。 – 2011-06-04 22:19:29