我有一个场景,我想使用方法组语法而不是匿名方法(或lambda语法)来调用函数.
该函数有两个重载,一个需要一个Action,另一个需要一个Func<string>.
我可以愉快地使用匿名方法(或lambda语法)调用两个重载,但如果我使用方法组语法,则会获得Ambiguous调用的编译器错误.我可以明确的解决方法铸造到Action或Func<string>,但不认为这应该是必要的.
任何人都可以解释为什么应该要求显式演员表.
代码示例如下.
class Program
{
static void Main(string[] args)
{
ClassWithSimpleMethods classWithSimpleMethods = new ClassWithSimpleMethods();
ClassWithDelegateMethods classWithDelegateMethods = new ClassWithDelegateMethods();
// These both compile (lambda syntax)
classWithDelegateMethods.Method(() => classWithSimpleMethods.GetString());
classWithDelegateMethods.Method(() => classWithSimpleMethods.DoNothing());
// These also compile (method group with explicit cast)
classWithDelegateMethods.Method((Func<string>)classWithSimpleMethods.GetString);
classWithDelegateMethods.Method((Action)classWithSimpleMethods.DoNothing);
// These both error with "Ambiguous invocation" (method group)
classWithDelegateMethods.Method(classWithSimpleMethods.GetString);
classWithDelegateMethods.Method(classWithSimpleMethods.DoNothing);
}
}
class ClassWithDelegateMethods
{
public void Method(Func<string> func) { /* do something …Run Code Online (Sandbox Code Playgroud) 我偶然发现了这种(在我看来是错误的)奇怪的行为,如果有人能告诉我为什么编译器会这样,或者也许我很幸运并发现了编译器错误,我将不胜感激;-)
全部都是针对 .net6.0 编译的(使用 VS 2022)
这是代码的第一个版本:
internal class Program
{
private static void Main(string[] args)
{
long longValue = 0;
string stringValue = "";
bool boolValue = false;
DateTime dateTimeValue = DateTime.Now;
double doubleValue = 0;
Console.Write("expect long => ");
SetValue(val => longValue = val);
Console.Write("expect string => ");
SetValue(val => stringValue = val);
Console.Write("expect bool => ");
SetValue(val => boolValue = val);
Console.Write("expect DateTime => ");
SetValue(val => dateTimeValue = val);
Console.ReadKey();
}
private static void SetValue(Action<long> setter) …Run Code Online (Sandbox Code Playgroud)