请考虑以下代码.看起来完全有效的C#代码对吗?
//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
};
}
}
Run Code Online (Sandbox Code Playgroud)
我得到一个编译错误'委托'动作'不接受0参数.使用(Microsoft)C#4.0编译器在指定位置.请注意,您必须在另一个项目中声明ActionSurrogate才能显示此错误.
它变得更有趣:
// Project A, File 1
public static class Class1 {
public static void ThisWontCompile() …Run Code Online (Sandbox Code Playgroud) 如果我有以下代码,我应该只调用Action还是应该调用Action.Invoke?
public class ClassA
{
public event Action<string> OnAdd;
private void SomethingHappened()
{
if (OnAdd != null)
OnAdd("It Happened"); //Should it be OnAdd.Invoke("It Happened") ???????
}
}
public class ClassB
{
public ClassB()
{
var myClass = new ClassA();
myClass.OnAdd += Add;
}
private void Add(string Input)
{
//do something
}
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
'Delegate'System.Action'不带0个参数.' 这是一个C#编译器错误(lambdas +两个项目)吗?
当我在做一个使用大量lambda用法的测试框架时,我偶然发现了一个解析器bug.
public class CSpecTestRunnerSpec : CSpecFacade<CSpecTestRunner>
{
public CSpecTestRunnerSpec()
: base(new CSpecTestRunner())
{
CreateOperations();
}
private MyClassSpec myClassSpec;
private DescribeAll run_on_type;
protected override void BeforeOperation()
{
myClassSpec = new MyClassSpec();
}
private void CreateOperations()
{
run_on_type =
(@it, @do) =>
{
@it("Runs all of the operations contained in a type");
@do.RunTestOnType(myClassSpec.GetType());
};
}
Run Code Online (Sandbox Code Playgroud)
DescribeAll委托来自基类,它的界面如下所示:
编辑代码看起来像这样:
public delegate void DescribeAll(Action<string> description, TClass objSpec);
Run Code Online (Sandbox Code Playgroud)
我得到的例外是"委托行动不带1个参数"但它完全有效!并在我的类的代码中添加一个虚拟委托后:
private Action<string> dummy;
Run Code Online (Sandbox Code Playgroud)
它开始起作用了.:-)
相比之下,相同的代码在单声道中没有错误的情况下工作,没有虚拟委托,它在使用NET 3.5和4.0的多台机器上进行了测试.
所以我的问题是,这是编译器方面还是我方的错误?以及如何解决问题?
ps框架在codeplex上,因此您可以获得完整的代码并自行测试.