相关疑难解决方法(0)

'委托'System.Action'不带0个参数.' 这是一个C#编译器错误(lambdas +两个项目)吗?

请考虑以下代码.看起来完全有效的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)

c# lambda compiler-errors compiler-bug

42
推荐指数
2
解决办法
2万
查看次数

使用委托和Lambda的奇怪行为

作为在我正在开发的库中引入延迟格式化评估的一种方法,我已经定义了委托

public delegate string MessageFormatterDelegate(string message, params object[] arguments);
public delegate string MessageFormatterCallback(MessageFormatterDelegate formatterDelegate);
Run Code Online (Sandbox Code Playgroud)

以及下一课的内容

public static class TestClass
{
    public static string Evaluate(MessageFormatterCallback formatterCallback)
    {
        return (formatterCallback(String.Format));
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这表现得非常奇怪:从外部项目运行时,语句

Console.WriteLine(TestClass.Evaluate(message => message("{0},{1},{2}", 1, 2, 3)));
Run Code Online (Sandbox Code Playgroud)

并没有编译,与错误而失败

Error   1   Delegate 'MessageFormatterDelegate' does not take 4 arguments
Run Code Online (Sandbox Code Playgroud)

而

Console.WriteLine(TestClass.Evaluate((MessageFormatterDelegate message) => message("{0},{1},{2}", 1, 2, 3)));
Run Code Online (Sandbox Code Playgroud)

编译和工作没有问题,1,2,3在控制台中打印.为什么我必须message使用MessageFormatterDelegate第二个lambda表达式中的类型限定参数?有没有办法来控制这种行为?

c# lambda .net-3.5

15
推荐指数
2
解决办法
1089
查看次数

标签 统计

c# ×2

lambda ×2

.net-3.5 ×1

compiler-bug ×1

compiler-errors ×1