'委托'System.Action' 不接受 0 个参数.这是 C# 编译器错误(lambdas + 两个项目)吗? [英] 'Delegate 'System.Action' does not take 0 arguments.' Is this a C# compiler bug (lambdas + two projects)?
问题描述
考虑下面的代码.看起来完全有效的 C# 代码对吗?
Consider the code below. Looks like perfectly valid C# code right?
//Project B
using System;
public delegate void ActionSurrogate(Action addEvent);
//public delegate void ActionSurrogate2();
// Using ActionSurrogate2 instead of System.Action results in the same error
// Using a dummy parameter (Action<double, int>) results in the same error
// Project A
public static class Class1 {
public static void ThisWontCompile() {
ActionSurrogate b = (a) =>
{
a(); // Error given here
};
}
}
我收到编译器错误Delegate 'Action' 不接受 0 个参数."在指定位置使用(Microsoft)C# 4.0 编译器.请注意,您必须在不同的项目中声明 ActionSurrogate 才能显示此错误.
I get a compiler error 'Delegate 'Action' does not take 0 arguments.' at the indicated position using the (Microsoft) C# 4.0 compiler. Note that you have to declare ActionSurrogate in a different project for this error to manifest.
变得更有趣了:
// Project A, File 1
public static class Class1 {
public static void ThisWontCompile() {
ActionSurrogate b = (a) => { a(); /* Error given here */ };
ActionSurrogate c = (a) => { a(); /* Error given here too */ };
Action d = () => { };
ActionSurrogate c = (a) => { a(); /* No error is given here */ };
}
}
我是不是在这里偶然发现了一个 C# 编译器错误?
Did I stumble upon a C# compiler bug here?
请注意,对于喜欢使用 lambdas 并试图创建数据结构库以供将来使用的人来说,这是一个非常烦人的错误......(我)
Note that this is a pretty annoying bug for someone who likes using lambdas a lot and is trying to create a data structures library for future use... (me)
删除了错误的案例.
我复制并精简了我的原始项目以实现这一目标.这就是我新项目中的所有代码.
I copied and stripped my original project down to the minimum to make this happen. This is literally all the code in my new project.
推荐答案
这可能是类型推断的问题,显然编译器将 a
推断为 Action
而不是 Action
(它可能认为 a
是 ActionSurrogate
,它适合 Action
签名).尝试明确指定 a
的类型:
This probably is a problem with type inferance, apperently the compiler infers a
as an Action<T>
instead of Action
(it might think a
is ActionSurrogate
, which would fit the Action<Action>>
signature). Try specifying the type of a
explicitly:
ActionSurrogate b = (Action a) =>
{
a();
};
如果不是这种情况 - 可能会检查您的项目是否有任何采用一个参数的自定义Action
委托.
If this is not the case - might check around your project for any self defined Action
delegates taking one parameter.
这篇关于'委托'System.Action' 不接受 0 个参数.这是 C# 编译器错误(lambdas + 两个项目)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!