请考虑以下代码.看起来完全有效的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) 作为在我正在开发的库中引入延迟格式化评估的一种方法,我已经定义了委托
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表达式中的类型限定参数?有没有办法来控制这种行为?