0

I have the following interface in my assembly

IGenericInterface<T1, T2>

and some classed who implement this interface

class FirstClass : IGenericInterface<Cat, Dog>
class SecondClass : IGenericInterface<Horse, Cow>

I need to write something like this using reflection

for each class that implements IGeiericInterface<,>
Console.WriteLine("Class {0} implements with {1}, {2}")

and the output should be

Class FirstClass implements with Cat, Dog
Class SecondClass implements with Horse, Cow
Raffaeu
  • 6,694
  • 13
  • 68
  • 110
  • Okay, that sounds feasible. How far have you got so far? Oh, and do you need to support `class ThirdClass : IGenericInterface` as well? – Jon Skeet Jun 26 '14 at 09:39
  • What is your question? – O. R. Mapper Jun 26 '14 at 09:39
  • 1
    possible duplicate of [Finding out if a type implements a generic interface](http://stackoverflow.com/questions/1121834/finding-out-if-a-type-implements-a-generic-interface) – Jacob Seleznev Jun 26 '14 at 09:40
  • So far I can easily say this: var resolver = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsAssignableFrom(typeof (ITypeConverter<,>))); But the collection is empty – Raffaeu Jun 26 '14 at 09:46

1 Answers1

1

Try this:

var assembly = Assembly.GetExecutingAssembly(); //or whatever else

        var types =
            from t in assembly.GetTypes()
            from i in t.GetInterfaces()
            where i.IsGenericType && i.GetGenericTypeDefinition().Equals(typeof(IFoo<,>))
            select new 
            {
                Type = t,
                Args = i.GetGenericArguments().ToList()
            };

        foreach (var item in types)
        {
            Console.WriteLine("Class {0} implements with {1}, {2}", item.Type.Name, item.Args[0].Name, item.Args[1].Name);
        }

UPDATE: As requested by a commenter, a little summary of what the code does.

  1. extracts all the types exposed by an assembly
  2. extracts all the interfaces implemented by those types
  3. takes only those types that implement the specified open generic interface
  4. selects those types along with the type arguments that close the generic type
  5. Writes on the console
MatteoSp
  • 2,940
  • 5
  • 28
  • 36
  • Perfect this is what I meant – Raffaeu Jun 26 '14 at 09:54
  • 1
    An answer with code for copy and pasting without any explanations may help the OP in their current question, but probably does not help them understand how this problem, and similar problems, can be solved. This is even more true for future visitors with similar, but not the same problem, who cannot benefit from a copy-and-paste answer at all. – O. R. Mapper Jun 26 '14 at 11:32
  • I really think the code already was clear and self explaining. Anyway I added what you asked for – MatteoSp Jun 26 '14 at 13:57