假设我有一个通用接口(interface) IFace<T, U>
. T
和 U
可以通过一些额外的方式进行约束,但我认为这与问题无关。
我想创建一个新的通用类 GenClass
具有以下定义:
class GenClass<T> where T: IFace
即我想告诉编译器 GenClass
应该处理 IFace
的任何实现不指定通用类型。
这可能吗,还是我需要指定 T
和 U
通用参数?
我试过写 IFace
以及IFace<>
或 IFace<,>
,但编译器总是不合适 - 所以我认为这是不可能完成的。不过,也许我的做法有误?
最佳答案
Is this possible, or do I NEED to specify the T and U generic parameters?
恐怕你需要它们。你需要有
class GenClass<T, TX, TY> where T : IFace<TX, TY>
这是假设您不能创建通用接口(interface)派生的非通用 IFace
接口(interface) - 这通常是最简单的方法:
public interface IFace
{
// Include anything that doesn't need the type parameters here
}
public interface IFace<T1, T2> : IFace
{
// Include anything that needs the type parameters here
}
然后您可以:
class GenClass<T> where T : IFace
因为现在非通用接口(interface)确实存在。
关于c# - 通用类和简化约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45006764/