[英]C# - Generic interface that extends generic parameter
Is it possible to define a generic interface that extends the interface's generic parameter?是否可以定义一个扩展接口泛型参数的泛型接口?
Eg (this doesn't compile since inheriting T
is not possible)例如(这不会编译,因为继承T
是不可能的)
public interface IInsecurableService<T>: T { }
This way I'd like to add services to a DI container that are capable of some functions, while the same service without the extensions does still exists / can still be registered.通过这种方式,我想将服务添加到具有某些功能的 DI 容器中,而没有扩展的相同服务仍然存在/仍然可以注册。
ECMA-335 , which defines the CLR, explicitly excludes this scenario , and gives a rationale (section §9.1, my bold):定义 CLR 的ECMA-335明确排除了这种情况,并给出了理由(第 9.1 节,我的粗体):
A generic parameter, on its own, cannot be used to specify the base class, or any implemented interfaces.泛型参数本身不能用于指定基类或任何已实现的接口。 So, for example,
.class ... G``1<T> extends !0
is invalid.因此,例如,.class ... G``1<T> extends !0
是无效的。 However, it is valid for the base class, or interfaces, to use that generic parameter when nested within another generic type.但是,当嵌套在另一个泛型类型中时,基类或接口使用该泛型参数是有效的。 For example,.class ... G``1<T> extends class H``1<!0>
and.class ... G``1<T> extends class B``2<!0,int32>
are valid.例如,.class ... G``1<T> extends class H``1<!0>
和.class ... G``1<T> extends class B``2<!0,int32>
是有效的。[ Rationale: This permits checking that generic types are valid at definition time rather than at instantiation time. [基本原理:这允许检查泛型类型在定义时是否有效,而不是在实例化时。 eg, in
.class ... G``1<T> extends !0
, we do not know what methods would override what others because no information is available about the base class;例如,在.class ... G``1<T> extends !0
,我们不知道哪些方法会覆盖其他方法,因为没有关于基类的信息; indeed, we do not even know whetherT
is a class: it might be an array or an interface.事实上,我们甚至不知道T
是否是一个类:它可能是一个数组或一个接口。 Similarly, for.class ... C``2<(!1)T,U>
where we are in the same situation of knowing nothing about the base class/interface definition.类似地,对于.class ... C``2<(!1)T,U>
,我们处于同样的情况,对基类/接口定义一无所知。 end rationale ]结束理由]
ECMA-334 , which defines the C# language spec, also excludes it (section §18.2.4):定义 C# 语言规范的ECMA-334也将其排除在外(第 18.2.4 节):
The explicit base interfaces can be constructed interface types (§9.4, §18.2).显式基接口可以是构造接口类型(第 9.4 节、第 18.2 节)。 A base interface cannot be a type parameter on its own, though it can involve the type parameters that are in scope.基接口本身不能是类型参数,尽管它可以涉及范围内的类型参数。
Also section §15.2.4.2还有第 §15.2.4.2 节
The base class specified in a class declaration can be a constructed class type (§9.4).类声明中指定的基类可以是构造类类型(第 9.4 节)。 A base class cannot be a type parameter on its own (§9.5), though it can involve the type parameters that are in scope.基类本身不能是类型参数(第 9.5 节),尽管它可以涉及范围内的类型参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.