单调的协方差编译异常

寻求

我正在尝试在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;

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

Example1.cs(22,39):

错误CS0266:无法将类型隐式转换System.Collections.Generic.IEnumerable<string>System.Collections.Generic.IEnumerable<object>存在显式转换(您是否缺少演员表?)

Example1.cs(40,36):

错误CS0029:无法将类型隐式转换System.Action<object>System.Action<string>

我可以通过强制转换来解决第一个问题:“ IEnumerable objects =(IEnumerable)strings;”,但是我不确定如何解决第二个问题。基本上,我不知道为什么从MSDN代码的编译中会出错。

我使用单声道Mono C# compiler version 3.12.0.0进行编译。可能是什么问题?

寻求

问题是我使用gmcs编译器,当我用dmcs编译代码时mcs,代码可以正常编译。

从Mono页面(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.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章