问题描述
由于引入懒格式评估在图书馆我正在开发的一种手段,我已经定义了代表
As a means of introducing lazy formatting evaluation in a library I am developing, I have defined the delegates
public delegate string MessageFormatterDelegate(string message, params object[] arguments);
public delegate string MessageFormatterCallback(MessageFormatterDelegate formatterDelegate);
和沿以下类的东西线
public static class TestClass
{
public static string Evaluate(MessageFormatterCallback formatterCallback)
{
return (formatterCallback(String.Format));
}
}
然而,这行为很奇怪:从运行时的外部的项目,该语句
Console.WriteLine(TestClass.Evaluate(message => message("{0},{1},{2}", 1, 2, 3)));
确实不是的编译,有错误失败
does not compile, failing with the error
Error 1 Delegate 'MessageFormatterDelegate' does not take 4 arguments
而
Console.WriteLine(TestClass.Evaluate((MessageFormatterDelegate message) => message("{0},{1},{2}", 1, 2, 3)));
编译和工作,没有任何问题,印刷 1,2,3
在控制台中。为什么我要限定的消息
的说法与 MessageFormatterDelegate
键入第二拉姆达EX pression?有没有什么办法可以circunvent这种行为?
compiles and works with no problems, printing 1,2,3
in the console. Why do I have to qualify the message
argument with MessageFormatterDelegate
type in the second lambda expression? Is there any way to circunvent this behaviour?
推荐答案
编辑:好的,我现在已经有了一个非常短的例子的和的一种解决方法
Okay, I've now got a much shorter example and a workaround.
第一个源文件, External.cs
:
public delegate string Callback(System.Action<string> x);
二源文件, test.cs中
:
class Test
{
static void Main()
{
Callback callback = action => action("hello");
}
}
与编译:
> csc /target:library External.cs
> csc Test.cs /r:External.cs
错误:
代表行动不带1个参数
解决方法:主
方法的主体更改为:
Workaround: change the body of the Main
method to:
Callback callback = action => action.Invoke("hello");
...或者包括委托声明中使用它的同一个程序集。
... or include the delegate declaration in the same assembly which uses it.
这肯定看起来像我的错误。当编译器知道类型富
是一个特定的委托类型,那么 FOO(ARG)
和 foo.Invoke(ARG)
应该是等价的。
This definitely looks like a bug to me. When the compiler knows that the type of foo
is a particular delegate type, then foo(arg)
and foo.Invoke(arg)
should be equivalent.
将寄给埃里克利珀...
Will mail Eric Lippert...
这篇关于奇怪的行为使用委托和Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!