如何更正警告CS1707
本文关键字:CS1707 警告 何更正 | 更新日期: 2023-09-27 17:58:21
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:由于新的语言规则,Delegate"ConsoleApplication1.BreakingChange.SampleDelegate"绑定到"ConsoleAApplication1.Breaking.Derived.CandidateAction(object("而不是"ConsoleAapplications1.BreakingChange.CandidateAction(string("''Program.cs(23,25(:(相关位置(''Program.cs(16,21(:(相关位置(
问题:我知道是什么引起了这个警告,也知道背后的原因。然而,我不知道是什么修复它的最佳方法?
1> 重新定义功能(即(更改功能签名
2> 我们可以在下面的行中显式调用BreakingChange.CandidateAction吗?
SampleDelegate factory = new SampleDelegate(x.CandidateAction);
好吧,有多种方法可以"修复"这个问题,这取决于你想做什么,也可以做什么。
就我个人而言,我会在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)