Interface generalizations and enumerations

If there is a set of classes that implement the interface.

interface IMyinterface<T>
{
    int foo(T Bar);
}

      

I want to shove them all into a list and list through them.

 List<IMyinterface> list
 foreach(IMyinterface in list)
 // etc...  

      

but the compiler wants to know what T. is. Can I do it? How can I solve this problem?

+1


source to share


3 answers


There is no type IMyinterface, only the type IMyinterface`1 exists, which requires a type argument. You can create type IMyinterface: -

interface IMyinterface { ... }

      

then we inherit from it



interface IMyinterface<T> : IMyinterface { ... }

      

You will need to move any members you would like to use in the foreach loop into the definition of IMyinterface.

+7


source


If you plan on calling a method with a T in the signature, the answer is that you can't. Otherwise, you can do what anthonywjones suggests.



+1


source


You still need to tell the compiler that T at some point, but only what you asked can be done:

 interface IMyinterface
{
    int foo<T>(T Bar);
}

List<IMyinterface> list = new List<IMyinterface>();
foreach(IMyinterface a in list){}

      

+1


source







All Articles