[英]Generic in type constraint
I'm struggling with some generics. 我正在努力研究一些仿制药。 The following is my setup:
以下是我的设置:
interface I<T> { }
[...]
void Add<T>(T obj) where T : I<??> { }
How can I ensure that T
in the Add
method implements I
? 如何确保
Add
方法中的T
实现I
?
The following signature will allow Add
to take any T
that implements I<>
with any type parameters. 以下签名将允许
Add
使用任何类型参数获取任何实现I<>
T
void Add<T,S>(T obj) where T : I<S> {
}
The downside of using this method signature is that type inference doesn't kick in and you have to specify all the type parameters, which looks downright silly: 使用此方法签名的缺点是类型推断没有启动,您必须指定所有类型参数,这看起来非常愚蠢:
blah.Add<I<int>, int>(iInstance);
A much simpler approach is to use the below signature: 一种更简单的方法是使用以下签名:
void Add<T>(I<T> obj) {
}
您还需要传递T参数来添加。
void Add<TI, TAny>(TI obj) where TI : I<TAny>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.