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

发布于 2024-08-21 19:29:47 字数 857 浏览 4 评论 0原文

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

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
}

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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薄荷梦 2024-08-28 19:29:47

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

this.GetType() or I am missing something?

枕梦 2024-08-28 19:29:47
MyScheduledService svc = this as MyScheduledService;
if (svc != null)
{
    // it is a MyScheduledService, and you can work with svc
}

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文