返回实现的正确类型签名
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>'
但是:
RA : A
,所以对T : A
有效
RB : B<RA>
,所以它是RB : B<T : A>
并且对TT : B <T : A>
有效
- 最后
RK : K<RA, RB>
,所以是RK : K<T : A, TT : B<T>>
所以应该也是有效的
问题:
我的逻辑错在哪里?
什么签名 GetR()
必须能够 return 作为 K<A, B<A>>
实现 K
的任何东西?
Where is the error in my logic?
你有一个对任何 T
和 TT
通用的方法(给定一些限制)但是你 return 一个 特定的 实现.如果您使用 RA
和 RB
以外的任何类型调用 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>;
}
如果 T
和 TT
不是 RA
和 RB
.
,那么 return null
在以下情况下:
/** 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>'
但是:
RA : A
,所以对T : A
有效
RB : B<RA>
,所以它是RB : B<T : A>
并且对TT : B <T : A>
有效
- 最后
RK : K<RA, RB>
,所以是RK : K<T : A, TT : B<T>>
所以应该也是有效的
问题:
我的逻辑错在哪里?
什么签名
GetR()
必须能够 return 作为K<A, B<A>>
实现K
的任何东西?
Where is the error in my logic?
你有一个对任何 T
和 TT
通用的方法(给定一些限制)但是你 return 一个 特定的 实现.如果您使用 RA
和 RB
以外的任何类型调用 K
,则 return 类型将不兼容。
What signature should
GetR()
have to be able to return asK<A, B<A>>
anything that implementsK
?
您的 签名 就是这样做的 - 这是导致错误的特定 return 值。你可以这样做:
public K<T, TT> GetR<T, TT>() where T : A where TT : B <T> {
return rk as K<T, TT>;
}
如果 T
和 TT
不是 RA
和 RB
.
null