How to reflect types that have a generic interface and get this type of generic

My first goal is to filter types based on a specific interface with a common one.

My second goal is to get the type of the most common parameter.

public UserService : IUserService, IDisposable, IExportableAs<IUserService>
{
  ...
}

I cannot assume the structure of the class, its interfaces (if any) or the same. The only thing I know, I am aiming ExportableAs<T>at my general assembly, which was used to create this plugin. But still I need to dynamically register the type.

So, I use a common interface for marking an exported type. In this case, it is IUserService. I do this assuming some kind of excellent Linq query might give me what I want. But I have small problems.

Here is what I still have:

assembly.GetTypes()
    .Where(t => t.GetInterfaces().Any(i => 
                i.IsGenericType &&
                i.GetGenericTypeDefinition() == typeof(IExportableAs<>))
            ).ToList()
    .ForEach(t => _catalogs.Add(
            new ComposablePart()
            {
                Name = t.FullName,
                Type = t // This is incorrect
            })
        );

, " ". UserService.

:

  • IExportableAs<T> (IUserService )
  • ( UserService)

, ( ): , .

linq .

!

+5
1

assembly.GetTypes().SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i })
    .Where(ti => ti.i.IsGenericType &&
                 ti.i.GetGenericTypeDefinition() == (typeof(IExportableAs<>)))
    .Select(ti => new ComposablePart() {
        Name = ti.t.FullName,
        Type = ti.i.GetGenericArguments()[0]
    });

[Edit] , , , . , .NET Framework . , , .

+4

All Articles