代码之家  ›  专栏  ›  技术社区  ›  Alex

从泛型基类获取实现的类型

  •  2
  • Alex  · 技术社区  · 14 年前

    我可能完全错了标题,但基本上,我有以下基本类:

    public class ScheduleableService<T> : ServiceBase
            where T : IJob
    {
            var x = typeof(T);
    }
    

    实现这一点类似于:

    public class MyScheduledService: ScheduleableService<MyScheduledJob>
    {
        //MyScheduledJob implements IJob
    }
    

    基本上,我需要的是在我的基类可调度服务中,以便能够掌握我的调度服务类型。- 我有什么办法不把它传进去就可以做到这一点吗?

    然而,下面的作品很难看……

    public class ScheduleableService<T, S> : ServiceBase
        where T : IJob
        where S : ServiceBase
    {
    
        var x = typeof(T);
        var y = typeof(S);
    }
    

    实施:

    public class MyScheduledService: ScheduleableService<MyScheduledJob,
                                                         MyScheduledService>
    {
        //MyScheduledJob implements IJob
    }
    
    2 回复  |  直到 14 年前
        1
  •  11
  •   Anton Gogolev    14 年前

    this.GetType() 或者我错过了什么?

        2
  •  0
  •   Michael Bray    14 年前
    MyScheduledService svc = this as MyScheduledService;
    if (svc != null)
    {
        // it is a MyScheduledService, and you can work with svc
    }
    

    但你为什么要这么做?它可能指出了您的设计中的一个缺陷。基类不需要知道任何关于派生类型的信息。