返回实现的正确类型签名

Correct type signature for returning an implementation

在以下情况下:

/** contract */

abstract class A { }
abstract class B<T> where T : A { }   
abstract class K<M, N> where M:A where N: B<M>{}

/** implementation */

class RA : A { }
class RB : B<RA> { }
class RK : K<RA, RB> { }

/** usage/test */

class Test {
    RK rk = new RK();

    public K<T, TT> GetR<T, TT>() where T : A where TT : B <T> {
        return rk;
    }
}

编译器在 return rk 上报错:

Cannot convert expression type 'RK' to return type 'K<T,TT>'

但是:

问题:

Where is the error in my logic?

你有一个对任何 TTT 通用的方法(给定一些限制)但是你 return 一个 特定的 实现.如果您使用 RARB 以外的任何类型调用 K,则 return 类型将不兼容。

What signature should GetR() have to be able to return as K<A, B<A>> anything that implements K?

您的 签名 就是这样做的 - 这是导致错误的特定 return 值。你可以这样做:

public K<T, TT> GetR<T, TT>() where T : A where TT : B <T> {
    return rk as K<T, TT>;
}

如果 TTT 不是 RARB.

,那么 return null