为什么嵌套类中的隐式运算符方法无法编译?

Evg*_*hin 6 c# generics implicit inner-classes

这段代码给出了一个错误:

public class A<T>
    {
        public class B<T1> : A<T1>
        {
            public static implicit operator bool(B<T1> b) => true;
        }
    }

Run Code Online (Sandbox Code Playgroud)

但是,如果我将类分开,则没有错误:


  public class A<T> {     }

  public class B<T> : A<T>
  {
       public static implicit operator bool(B<T> b) => true;
  }
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 1

这个问题问得好。我发现您可以通过指定来消除错误A<T>.B<T1>

public static implicit operator bool(A<T>.B<T1> b) => true;
Run Code Online (Sandbox Code Playgroud)

所以然后我开始想知道为什么在这个特定的实例中你需要限定内部类,因为通常你不需要。

本质上,您编写的是一个隐式转换,它可以接受封闭类型以外的类型。请注意,A<int>.B<string>A<string>.B<string>是不同的类。

让我们使用普通方法而不是隐式转换来更清楚地说明发生的情况。

public class A<T>
{
    public class B<T1>
    {
        public static void F(B<T1> i) {}
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意没有继承子句。暂时先忍耐一下。这里B<T1>实际上的意思是A<T>.B<T1>。这意味着我们不能做这样的事情:

A<int>.B<string>.F(new A<string>.B<string>()); // cannot convert type ...
Run Code Online (Sandbox Code Playgroud)

所以看起来只要写B<T1>在转换中就可以了。但是当你引入继承条款时......

public class A<T>
{
    public class B<T1>: A<T1>
    {
        public static void F(B<T1> i) {}
    }
}

A<int>.B<string>.F(new A<string>.B<string>()); // suddenly this compiles
Run Code Online (Sandbox Code Playgroud)

这意味着您现在可以传递除A<T>.B<T1>隐式转换之外的其他内容,但这是不允许的。