简体   繁体   中英

Generic passing of interface and class implementing interface

I'm trying to create a method that through generics tries to pass an interface and a class. It should look something like this, but this does not build:

public static void Register<TInterface, TClass>() 
  where TClass     : TInterface 
  where TInterface : interface // <- doesn't compile
{
   ...
}

Is there any way to get this to work. The idea is to build a wrapper around an ioc container.

You cannot do it the way you want. The closest you will be able to achieve is by limiting TClass to inherit/implement the TInterface , but TInterface can also be a class (and TClass can also be an interface. Perhaps its worth noting that class does not mean class but any reference type. It can also be an interface )

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM