【发布时间】:2020-05-20 03:51:48
【问题描述】:
我正在尝试创建一个通过泛型尝试传递接口和类的方法。 它应该看起来像这样,但这不会构建:
public static void Register<TInterface, TClass>()
where TClass : TInterface
where TInterface : interface // <- doesn't compile
{
...
}
有没有办法让它工作。这个想法是围绕 ioc 容器构建一个包装器。
【问题讨论】:
-
c#中没有
where T : interface约束,只能使用接口名。你可以使用类似where TClass : class, TInterface -
为什么要放约束
: interface?如果我为TInterface提供抽象类,那会有什么错误? -
没有。您不能将类型参数约束到接口。一般来说,如果你发现你的泛型想要施加这样的约束,这通常表明你已经走得太远了,因为你可以用这些知识做没有多大意义的事情。只是为了外表而“很好地排列类型”。
-
这看起来你正在实现一种“穷人的依赖注入”。看看其他成熟的容器实现是怎么做的,会有
void Register<TService, TImplementation>() where TService: class where TImplementation : class, TService -
堆栈溢出有类似的问题stackoverflow.com/questions/1104229/…