Get the implemented type from a Generic Base Class
-
21-09-2019 - |
Question
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
}
Solution
this.GetType()
or I am missing something?
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow