【问题标题】:Generic passing of interface and class implementing interface接口的泛型传递和实现接口的类
【发布时间】: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&lt;TService, TImplementation&gt;() where TService: class where TImplementation : class, TService
  • 堆栈溢出有类似的问题stackoverflow.com/questions/1104229/…

标签: c# generics


【解决方案1】:

你不能按照你想要的方式去做。 最接近您将能够实现的是通过限制TClass 继承/实现TInterface,但TInterface 也可以是一个类(并且TClass 也可以是一个接口。也许值得注意的是class 确实不是指class,而是任何引用类型。也可以是interface)

public static void Register<TInterface, TClass>() 
  where TClass     : class, TInterface
  where TInterface : class
{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-12
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多