cuo*_*gle 23 c# covariance contravariance c#-4.0
假设我有接口和类:
public interface ITree {}
public class Tree : ITree {}
Run Code Online (Sandbox Code Playgroud)
由于IEnumerable<T>是协变,下面的代码行成功编译:
IEnumerable<ITree> trees = new List<Tree>();
Run Code Online (Sandbox Code Playgroud)
但是当我把它放入通用方法时:
public void Do<T>() where T : ITree
{
IEnumerable<ITree> trees = new List<T>();
}
Run Code Online (Sandbox Code Playgroud)
我从编译器得到编译错误:
错误1无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.IEnumerable'.存在显式转换(您是否缺少演员?)D:\ lab\Lab.General\Lab.General\Program.cs 83 40 Lab.General
为什么协方差在这种情况下不起作用?
ale*_*exn 26
这是因为方差仅适用于引用类型(类,接口和委托).添加一个类约束,它编译得很好:
public static void Do<T>() where T : class, ITree
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1987 次 |
| 最近记录: |