c# - 如果将委托(delegate)定义放在另一个项目中,编译会失败吗?

标签 c# visual-studio-2010 compiler-errors

更新:我已将其归档为 an issue on Microsoft Connect,如果您可以重现此内容和/或希望看到此问题得到修复,请帮助投票解决那边的问题。


几个小时以来,我一直在努力解决这个问题。
非常感谢您能想到的任何想法/建议。

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

问题是,如果您在同一个控制台应用程序项目中拥有所有 3 个文件。应用程序可以正常编译和运行。

但是,如果我在“库”项目中有 Class.csDefinitions.cs,该项目是从只有 Program.cs 文件,编译失败:

  • 委托(delegate) Act 不接受 2 个参数。
  • 无法将 lambda 表达式转换为委托(delegate)类型“DC.Lib.Produce”,因为 block 中的某些返回类型不能隐式转换为委托(delegate)返回类型 ...

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

我使用的是 VS2010 RTW 专业版。

最佳答案

很有趣。我认为您在 C# 编译器中发现了一个真正的错误 - 尽管我可能遗漏了一些细微的东西。我写了一个稍微简化的版本,它避免了重载等的可能性,并且省去了额外的方法:

// Definitions.cs
public interface IData { }
public delegate IData Foo(IData input);
public delegate IData Bar<T>(IData input, T extraInfo);
public delegate Foo Produce<T>(Bar<T> next);

// Test.cs
class Test
{
    static void Main()
    {
        Produce<string> produce = 
            next => input => next(input, "This string should appear.");
    }    
}

作为一个程序集编译的演示,没有错误:

> csc Test.cs Definitions.cs

编译为两个有错误的程序集的演示:

> csc /target:library Definitions.cs
> csc Test.cs /r:Definitions.dll

Test.cs(5,43): error CS1662: Cannot convert lambda expression 
        to delegate type 'Produce<string>'
        because some of the return types in the block are not 
        implicitly convertible to the delegate return type
Test.cs(5,52): error CS1593: Delegate 'Bar' does not take 2 arguments

我想不出任何为什么这在不同的程序集之间应该不同,因为一切都是公开的。除了内部原因外,规范很少讨论程序集边界。

有趣的是,对于 C# 3 和 4 编译器,我都遇到了同样的错误。

现在给 Eric 和 Mads 发电子邮件...

编辑:请注意,您可以使用显式参数列表解决此问题。例如,在我的示例代码中,这将起作用:

Produce<string> produce =
    (Bar<string> next) => input => next(input, "This string should appear.");

关于c# - 如果将委托(delegate)定义放在另一个项目中,编译会失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3276578/

相关文章:

java - 使用泛型和扩展特征时,Groovy静态编译失败

c# - Visual Studio 如何在调试期间显示 System.Double?

c++ - MS VC2010 - 双向斜线路径

C# XNA Xbox,本例可选参数不可选

c# - 在 C# 中调用函数直到满足条件

c++ - 为什么将 0.1f 更改为 0 会使性能降低 10 倍?

gcc - “small-data section exceeds 64KB..” “additional relocation overflows omitted from the output 1>collect2.exe: error: ld returned 1 exit status”

c# - 将程序集添加到gac时csharpcodeprovider无法编译

c# - 如何搜索各种类型的属性

c# - Windows 服务 : The underlying provider failed on Open 上的间歇性错误