[英]How do I use a generic type within a generic class declaration?
The following code... 以下代码...
class Repository<T> where T : Func<TIn, TOut>
{
//...
}
causes VS to complain that "the type or namespace name 'TIn'/'TOut' could not be found." 使VS抱怨“找不到类型或名称空间名称'TIn'/'TOut'”。
Is there any way to do this? 有什么办法吗?
If Func
itself was a generic class, then yes you could via: 如果Func
本身是泛型类,则可以通过以下方式进行:
class Repository<T, TIn, TOut> where T: Func<TIn, TOut>
However, you couldn't do this with Func
as it can only be constrained by an interface/non-sealed class or a type parameter. 但是,您无法使用Func
进行此操作,因为它只能受到接口/非密封类或类型参数的约束。
As an alternative, you could pass the Func
in as a constructor argument and it would work ie 作为替代方案,您可以将Func
作为构造函数参数传入, 它将起作用,即
class Repository<TIn, TOut>
{
public Repository(Func<TIn, TOut> func)
{
...
}
}
Not really sure if that would give you what you're after though. 不确定是否会给您带来什么。
Since you already know the type you want, there's no need to put a constraint on it. 由于您已经知道所需的类型,因此无需对其施加约束。 I think what you want is this: 我认为您想要的是:
class Repository<TIn, TOut>
{
public void someMethod(Func<TIn, TOut> func)
{
}
}
You must specify the "inputs" for TIn
and TOut
in the definition of your class, otherwise, the compiler doesn't figure out from where took that 您必须在类的定义中指定TIn
和TOut
的“输入”,否则,编译器将无法确定从何处获取该输入
class Repository<T, TIn, TOut> where T : Func<TIn, TOut>
{
//...
}
You can't constrain a type T
to Func because you can only constrain types to interfaces, non-sealed classes or type parameters. 您不能将类型T
约束为Func,因为您只能将类型约束为接口,非封闭类或类型参数。
If you could do it, it would look like this: 如果可以做到,它将如下所示:
class Repository<T, TIn, Tout> where T: Func<TIn, TOut>
{
//...
}
But you're not allowed to constrain to Func<>
, so the whole thing is doomed. 但是不允许您使用Func<>
,所以整件事注定了。
The error message from the compiler is: 来自编译器的错误消息是:
Error 1 'System.Func' is not a valid constraint. 错误1'System.Func'不是有效的约束。 A type used as a constraint must be an interface, a non-sealed class or a type parameter. 用作约束的类型必须是接口,非密封类或类型参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.