gpt4 book ai didi

c# - 单声道的逆变编译异常

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:33 25 4
gpt4 key购买 nike

我正在尝试在 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# - 单声道的逆变编译异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com