给定此类:public class Wrapper<T>{ public Wrapper(T value) { Value = value; } public T Value { get; } public static implicit operator Wrapper<T>(T value) { return new Wrapper<T>(value); }}此代码段无法编译:IEnumerable<int> value = new [] { 1, 2, 3 };Wrapper<IEnumerable<int>> wrapper = value;错误CS0266:无法将类型'System.Collections.Generic.IEnumerable <int>'隐式转换为'Spikes.Implicit.Wrapper <System.Collections.Generic.IEnumerable <int >>'。存在显式转换(您是否缺少演员表?)但是编译器对此非常满意:Wrapper<IEnumerable<int>> wrapper = new [] { 1, 2, 3 };为什么?
1 回答
www说
TA贡献1775条经验 获得超8个赞
C#语言规范明确指出了这一点:
6.4.1节允许的用户定义转换
对于给定的源类型S和目标类型T,如果S或T是可为空的类型,则让S0和T0引用其基础类型,否则S0和T0分别等于S和T。仅当满足以下所有条件时,才允许类或结构声明从源类型S到目标类型T的转换:
S0和T0是不同的类型。
S0或T0是在其中进行操作符声明的类或结构类型。
S0和T0都不是接口类型。
不包括用户定义的转换,不存在从S到T或从T到S的转换。
您的案件违反了条件的第3点。源类型是接口!
- 1 回答
- 0 关注
- 149 浏览
添加回答
举报
0/150
提交
取消