繁体   English   中英

从通用基类获取实现的类型

[英]Get the implemented type from a Generic Base Class

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

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

这个的实现是这样的:

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

基本上,我需要的是,在我的基类ScheduleableService中,能够获取MyScheduledService类型 - 有没有办法我可以做到这一点而不传递它。

以下作品,但是很难......

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
}

this.GetType()或我遗失了什么?

MyScheduledService svc = this as MyScheduledService;
if (svc != null)
{
    // it is a MyScheduledService, and you can work with svc
}

但为什么你需要这样做? 它可能表明您的设计存在缺陷。 基类应该永远不需要知道有关派生类型的任何信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM