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

此代码给出一个错误:

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

但是,如果我将这些类分开,则不会出现错误:


  public class A<T> {     }

  public class B<T> : A<T>
  {
       public static implicit operator bool(B<T> b) => true;
  }
qjjjjwqvcrrxx 回答:为什么嵌套类中的隐式运算符方法无法编译?

这是一个很好的问题。我发现您可以通过指定A<T>.B<T1>使错误消失:

public static implicit operator bool(A<T>.B<T1> b) => true;

因此,我开始怀疑为什么在这种特殊情况下您需要限定内部类的资格,因为通常您不需要。

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

让我们使用常规方法而不是隐式转换来更清楚地说明正在发生的事情。

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

请注意,没有继承子句。现在忍受我。这里的B<T1>实际上是A<T>.B<T1>。这意味着我们不能做这样的事情:

A<int>.B<string>.F(new A<string>.B<string>()); // cannot convert type ...

因此,在转换中只写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

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

本文链接:https://www.f2er.com/2877706.html

大家都在问