2015-02-06 62 views
2

我試圖編譯MSDN中的協變/反變化示例(https://msdn.microsoft.com/en-us/library/ee207183.aspx)。單變量編譯異常

​​

的問題是,我得到了兩個錯誤:

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

我覺得這與[Liskov的Substituion原理](http://en.wikipedia.org/wiki/Liskov_substitution_principle)和/或事實'IEnumerable '不是來自'IEnumerable '的第一個例子。一個簡單的'var objects = strings.Cast ().Tolist()'可能會修復你的第一個例子。 – 2015-02-06 22:41:24

+1

此功能與C#4,.NET 4.0一起添加,並會在以前的版本中產生這些錯誤。您的Mono是否瞄準4.0或更早版本的功能? – 2015-02-06 22:43:37

回答

2

問題是我用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.