【问题标题】:Get the implemented type from a Generic Base Class从通用基类中获取实现的类型
【发布时间】:2011-01-18 19:19:03
【问题描述】:

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

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
}

【问题讨论】:

  • 您是说要从ScheduleableService&lt;T&gt; 中访问MyScheduledService成员

标签: c# generics inheritance base-class


【解决方案1】:

this.GetType() 还是我遗漏了什么?

【讨论】:

    【解决方案2】:
    MyScheduledService svc = this as MyScheduledService;
    if (svc != null)
    {
        // it is a MyScheduledService, and you can work with svc
    }
    

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

    【讨论】:

      猜你喜欢
      • 2015-12-04
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 2010-10-08
      • 2020-07-23
      • 2018-10-10
      相关资源
      最近更新 更多