相关疑难解决方法(0)

泛型协方差和显式铸造

如果我尝试做:

IDictionary<uint, IEnumerable<string>> dict = new Dictionary<uint, List<string>>();
Run Code Online (Sandbox Code Playgroud)

我收到错误:

错误CS0266:无法将类型'System.Collections.Generic.Dictionary>'隐式转换为'System.Collections.Generic.IDictionary>'.存在显式转换(您是否错过了演员?)

如果我添加演员:

IDictionary<uint, IEnumerable<string>> dict = (IDictionary<uint, IEnumerable<string>>)new Dictionary<uint, List<string>>();
Run Code Online (Sandbox Code Playgroud)

然后它编译.

为什么我需要显式演员?它安全吗?我认为协方差的全部意义在于能够安全地隐式投射?

编辑: C#防止不相关的铸造,例如

string s = (string)0L;
Run Code Online (Sandbox Code Playgroud)

错误CS0030:无法将类型'long'转换为'string'

当您知道对象实际上是子类时,它确实允许显式向下转换相关类型:

Animal animal = new Cat();
Cat cat = (Cat)animal;
Run Code Online (Sandbox Code Playgroud)

我很困惑为什么编译器提供,并允许我显式转换为具有不兼容类型的IDictionary.

c# generics covariance

9
推荐指数
3
解决办法
2470
查看次数

标签 统计

c# ×1

covariance ×1

generics ×1