我正在尝试编译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 Mono C# compiler version 3.12.0.0
进行编译。可能有什么问题?
答案 0 :(得分:2)
问题是我使用gmcs
编译器,当我用dmcs
或mcs
编译代码时,代码编译得很好。
从单声道页面(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.