无法隐式"包装"IEnumerable

Pau*_*ney 8 c#

鉴于此类:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码段无法编译:

IEnumerable<int> value = new [] { 1, 2, 3 };
Wrapper<IEnumerable<int>> wrapper = value;
Run Code Online (Sandbox Code Playgroud)

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

但是编译器非常满意这个:

Wrapper<IEnumerable<int>> wrapper = new [] { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)

为什么?

Swe*_*per 6

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点.源类型是一个接口!