Get the implemented type from a Generic Base Class
-
21-09-2019 - |
문제
I may of worded the title completely wrong, but basically, I have the following base class:
public class ScheduleableService<T> : ServiceBase
where T : IJob
{
var x = typeof(T);
}
The implementation of this is something like:
public class MyScheduledService: ScheduleableService<MyScheduledJob>
{
//MyScheduledJob implements IJob
}
Basically, what I need, is in my base class ScheduleableService, to be able to get hold of the MyScheduledService type- Is there any way I can do this without passing it in.
The following works, however is ugly.....
public class ScheduleableService<T, S> : ServiceBase
where T : IJob
where S : ServiceBase
{
var x = typeof(T);
var y = typeof(S);
}
implementation:
public class MyScheduledService: ScheduleableService<MyScheduledJob,
MyScheduledService>
{
//MyScheduledJob implements IJob
}
해결책
this.GetType()
or I am missing something?
다른 팁
MyScheduledService svc = this as MyScheduledService;
if (svc != null)
{
// it is a MyScheduledService, and you can work with svc
}
But why would you need to do this? It possibly points to a deficiency in your design. The base class should never need to know anything about derived types.
제휴하지 않습니다 StackOverflow