相关疑难解决方法(0)

使用委托和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
查看次数

如果将委托定义放在另一个项目中,则编译失败?

更新:我已将此作为Microsoft Connect的问题提交,如果您可以重现这一点和/或希望看到此修复,请帮助在那里投票解决问题.


我一直试图解决这个问题几个小时了.
非常感谢您能想到的任何想法/建议.

首先,我有3个文件Class.cs Definitions.csProgram.cs.我已经在http://pastie.org/1049492粘贴了文件内容供您试用.

问题是,如果在同一个控制台应用程序项目中有所有3个文件.应用程序编译并运行得很好.

但是,如果我有Class.csDefinitions.cs在从它只有在主控制台应用程序项目中引用到"库"的项目Program.cs文件,编译失败:

  • 代表Act不接受2个论点.
  • 无法将lambda表达式转换为委托类型'DC.Lib.Produce',因为块中的某些返回类型不能隐式转换为委托返回类型...

这是一个包含3个项目的完整解决方案 - 其中1个包含所有文件,另一个包含在另一个项目中的定义:http:
//dl.dropbox.com/u/149124/DummyConsole.zip

我正在使用VS2010 RTW专业版.

c# compiler-errors visual-studio-2010

6
推荐指数
1
解决办法
671
查看次数

代表上的C#Parser Bug?

可能重复:
'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上,因此您可以获得完整的代码并自行测试.

c# compiler-errors

2
推荐指数
1
解决办法
427
查看次数