Reflection and Generics in .Net

2019-07-26 23:43发布

Ok...

I have the following interfaces:

  • IJobWrapper(Of T As IJob)
  • IJob

And the following abstracts:

  • JobWrapper(Of T as IJob) (Implements IJobWrapper(Of T))
  • Job1 (Implements IJob)
  • Job2 (Implements IJob)

So... First I find the wrapper abstract using:

Dim JobWrappers = AppDomain.
CurrentDomain.
GetAssemblies().
ToList().
SelectMany(Function(s) s.GetTypes()).
Where(Function(x) x.FullName.Contains("JobWrapper") And Not X.IsInterface).
First

This works fine (I'm aware it's a little inefficient but I can tidy it up when I've got a working version).

Then I use reflection to get all types which implement IJob (Similar to the above, I won't post code unless you need it) And do...

    For Each JobType In JobTypes
        Dim TypeArgs As Type() = {JobType.GetType}
        Dim WrappedJob = JobWrapperType.MakeGenericType(TypeArgs)
        ''Do some other stuff
    Next

This throws an exception. Specifically, this call:

JobWrapperType.MakeGenericType(TypeArgs)

Results in: GenericArguments[0], 'System.RuntimeType', on 'MyProject.Jobs.JobWrapper'1[T]' violates the constraint of type 'T'.

Now in this case, Job1 implements IJob. JobWrapper expects an IJob as it's type parameter.

Can someone please tell me how I can get a reference to the Types:

JobWrapper(Job1) and JobWrapper(Job2)

Thanks

As a little background: I'm loading assemblies into a new AppDomain and then loading all the IJobs from the assemblies loaded into that domain - hence having to use reflection. The Interfaces mentioned are defined in a common assembly referenced by both the current project and the ones containing the actual implementations of Job

1条回答
仙女界的扛把子
2楼-- · 2019-07-27 00:08

You've got one too many GetTypes - I think you just need:

For Each JobType In JobTypes
    Dim TypeArgs As Type() = {JobType}
    Dim WrappedJob = JobWrapperType.MakeGenericType(TypeArgs)
    ''Do some other stuff
Next
查看更多
登录 后发表回答