C#完全通用约束

时间:2016-09-10 12:54:16

标签: c# generics inheritance singleton

我有这样的情况:

abstract class DTAction<T_Owner> {
 public virtual void Process(T_Owner owner) { }
 // Other stuff...
}

abstract class SingletonAction<T_Owner, T_ActionImpl> : DTAction<T_Owner>
 where T_ActionImpl : SingletonAction<T_Owner, T_ActionImpl>, new() 
 where T_Owner : MyOwnerBase<T_Owner> {
      // just setting up the singleton here.
 }

 abstract class MyOwnerBase<T_Owner> : SomeOtherBase 
 where T_Owner : MyOwnerBase<T_Owner> {

 }

所以,这就是设置。我使用这样的:

class MyOwnerImpl : MyOwnerBase<MyOwnerImpl> { 
// specific work

// nested single-instance classes that do the processing on the "owner", which is this actual instance.
  class ActionA : SingletonAction<MyOwnerImpl, ActionA> {
    public override void Process(MyOwnerImpl owner) {
      // Processing A
    }
  }

  class ActionB : SingletonAction<MyOwnerImpl, ActionB> {
    public override void Process(MyOwnerImpl owner) {
      // Processing B
    }
  }
}

这是有效的,但我对继承规范有疑问。它允许我指定不正确的类型,例如:

class ActionB : SingletonAction<MyOwnerImpl, ActionA> {
     public override void Process(MyOwnerImpl owner) {
       // Processing B
     }
}

在调用ActionB.Instance时会返回ActionA的单例实例。编译器认为这是合法的,我还没有找到一种方法来指定我只想在上面的代码片段中使用ActionB。有什么方法可以解决这个问题吗?

0 个答案:

没有答案