c# - mono 的逆变编译异常

标签 c# mono

我正在尝试编译 MSDN 中的协方差/逆变示例 ( https://msdn.microsoft.com/en-us/library/ee207183.aspx )。

// Assignment compatibility.  
string str = "test";
// An object of a more derived type is assigned to an object of a less derived type.  
object obj = str;

// Covariance. 
IEnumerable<string> strings = new List<string>();
// An object that is instantiated with a more derived type argument  
// is assigned to an object instantiated with a less derived type argument.  
// Assignment compatibility is preserved. 
IEnumerable<object> objects = strings;

// Contravariance.            
// Assume that the following method is in the class:  
// static void SetObject(object o) { } 
Action<object> actObject = SetObject;
// An object that is instantiated with a less derived type argument  
// is assigned to an object instantiated with a more derived type argument.  
// Assignment compatibility is reversed. 
Action<string> actString = actObject;

问题是我遇到了两个错误:

示例1.cs(22,39):

error CS0266: Cannot implicitly convert type System.Collections.Generic.IEnumerable<string> to System.Collections.Generic.IEnumerable<object>. An explicit conversion exists (are you missing a cast?)

示例1.cs(40,36):

error CS0029: Cannot implicitly convert type System.Action<object>to System.Action<string>

我可以通过转换解决第一个问题:'IEnumerable objects = (IEnumerable)strings;',但我不确定如何解决第二个问题。基本上,我不知道为什么我在编译MSDN代码时遇到错误。

我使用单声道 Mono C# compiler version 3.12.0.0用于编译。可能出了什么问题?

最佳答案

问题是我使用了gmcs编译器,当我使用dmcsmcs编译代码时,代码编译得很好。

来自单色页面 ( http://www.mono-project.com/docs/about-mono/languages/csharp/ )

gmcs: compiler to target the 2.0 mscorlib.
smcs: compiler to target the 2.1 mscorlib, to build Moonlight applications.
dmcs: compiler to target the 4.0 mscorlib.

Starting with Mono version 2.11 a new unified compiler mcs is available. 
It replaces all previous runtime specific compilers (gmcs, dmcs, smcs). 
They still exist (as scripts only) to ease the migration path to mcs 
but we strongly recommend to use mcs.

关于c# - mono 的逆变编译异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376000/

相关文章:

c# - Tab按钮在windows窗体应用程序中切换到错误的控件

C# - 根据类型将对象转换为 IList<T>

c# - 如何改进 WPF 倒数计时器的时间格式

android - Mono For Android 应用内计费

c# - 了解 MEF System.Lazy<T,TMetaData>

c# - 如何计算滚动条拇指的大小?

asp.net - 基本的 Mono 安装不起作用

c# - TPL 能否在多个线程上运行任务?

.net - Mono 是 .NET 的子集吗?

macos - 单声道 pkg 在 mac 上永远验证