[英]C# generic parameters
Let's say I have some generic interface IMyInterface<TParameter1, TParameter2>
. 假设我有一些通用
interface IMyInterface<TParameter1, TParameter2>
。
Now, if I'm writing another class, generic on it's parameter T
: 现在,如果我正在编写另一个类,则它的参数
T
通用的:
CustomClass<T> where T : IMyInterface
how should this be done? 应该怎么做?
(current code won't compile, because IMyInterface
is dependent on TParameter, TParameter2
) . (当前代码不能编译,因为
IMyInterface
是依赖于TParameter, TParameter2
)。
I assume it should be done like: 我认为应该这样做:
CustomClass<T, TParameter1, TParameter2> where T: IMyInterface<TParameter1,
TParameter2>
but I might be wrong, could you advice me please? 但是我可能是错的, 请您告诉我一下吗?
It's exactly as you have it, you need to specify the TParameter1
and TParameter2
generic arguments in a class which requires a generic constraint on IMyInterface
: 这正是因为你拥有它,你需要指定
TParameter1
和TParameter2
在需要对通用约束的一类通用参数IMyInterface
:
public interface IMyInterface<TParameter1, TParameter2>
{
}
public class CustomClass<T, TParameter1, TParameter2>
where T : IMyInterface<TParameter1, TParameter2>
{
}
or you could have them fixed: 或者您可以修复它们:
public class CustomClass<T>
where T : IMyInterface<string, int>
{
}
Do you really want to use it as a constraint (with the 'where' keyword)? 您是否真的想将其用作约束(与“ where”关键字一起使用)? Here are some examples of straight implementation:
以下是一些直接实现的示例:
interface ITwoTypes<T1, T2>
class TwoTypes<T1, T2> : ITwoTypes<T1, T2>
Or, if you know the type(s) your class will use, you don't need a type parameter on the class: 或者,如果您知道您的类将使用的类型,则无需在类上使用类型参数:
class StringAndIntClass : ITwoTypes<int, string>
class StringAndSomething<T> : ITwoTypes<string, T>
If you are using the interface as a constraint and don't know the types to specify explicitly, then yes, you need to add the type parameters to the class declaration, as you supposed. 如果您使用接口作为约束并且不知道要显式指定的类型,那么可以,您需要按照预期的那样将类型参数添加到类声明中。
class SomethingAndSomethingElse<T, TSomething, TSomethingElse> where T : ITwoTypes<TSomething, TSomethingElse>
class StringAndSomething<T, TSomething> where T : ITwoTypes<string, TSomething>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.