.Net 中的反射和泛型
好的...
我有以下接口:
IJobWrapper(Of T As IJob)
IJob
以及以下摘要:
JobWrapper(Of T as IJob)
> (实现IJobWrapper(Of T)
)Job1
(实现IJob
)Job2
(实现IJob< /code>)
所以...首先我找到包装器抽象使用:
Dim JobWrappers = AppDomain.
CurrentDomain.
GetAssemblies().
ToList().
SelectMany(Function(s) s.GetTypes()).
Where(Function(x) x.FullName.Contains("JobWrapper") And Not X.IsInterface).
First
这工作正常(我知道它有点低效,但当我有一个工作版本时我可以整理它)。
然后我使用反射来获取所有实现 IJob
的类型(与上面类似,除非您需要,否则我不会发布代码)并且执行...
For Each JobType In JobTypes
Dim TypeArgs As Type() = {JobType.GetType}
Dim WrappedJob = JobWrapperType.MakeGenericType(TypeArgs)
''Do some other stuff
Next
这会引发异常。具体来说,此调用:
JobWrapperType.MakeGenericType(TypeArgs)
结果:GenericArguments[0], 'System.RuntimeType', on 'MyProject.Jobs.JobWrapper'1[T]' 违反了类型“T”的约束。
现在,在本例中,Job1
实现了 IJob
。 JobWrapper
需要一个 IJob
作为它的类型参数。
有人可以告诉我如何获得对类型的引用:
JobWrapper(Job1)
和 JobWrapper(Job2)
谢谢
作为一个小背景:我正在将程序集加载到一个新的 AppDomain,然后从加载到该域的程序集中加载所有 IJobs - 因此必须使用反射。提到的接口是在当前项目和包含 Job 实际实现的项目引用的通用程序集中定义的
Ok...
I have the following interfaces:
IJobWrapper(Of T As IJob)
IJob
And the following abstracts:
JobWrapper(Of T as IJob)
(ImplementsIJobWrapper(Of T)
)Job1
(ImplementsIJob
)Job2
(ImplementsIJob
)
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你有太多的
GetType
- 我认为你只需要:You've got one too many
GetType
s - I think you just need: