简体   繁体   English

改进此通用抽象类

[英]Improve this generic abstract class

I have the following abstract class design, I was wondering if anyone can suggest any improvements in terms of stronger enforcement of our requirements or simplifying implementing of the ControllerBase. 我有以下抽象类设计,我想知道是否有人可以就加强我们的要求的实施或简化ControllerBase的实施提出任何改进建议。

//Dependency Provider base
public abstract class ControllerBase<TContract, TType> where TType : TContract, class
{
    public static TContract Instance 
    {
        get { 
    return ComponentFactory.GetComponent<TContract, TType>(); 
            }
    }

 public TContract GetComponent<TContract, TType>() where TType : TContract, class
 {   
        component = (TType)Activator.CreateInstance(typeof(TType), true);
        RegisterComponentInstance<TContract>(component);
 }
}

//Contract
public interface IController
{
 void DoThing();
}

//Actual Class Logic
public class Controller: ControllerBase<IController,Controller>
{
 public void DoThing();

    //internal constructor
    internal Controller(){}

}


//Usage
public static void Main()
{
 Controller.Instance.DoThing();
}

The following facts should always be true, 以下事实应始终是真实的,

  • TType should always implement TContract (Enforced using a generic constraint) TType应该始终实现TContract (使用通用约束强制执行)

  • TContract must be an interface (Can't find a way to enforce it) TContract必须是一个接口(找不到强制执行的方法)

  • TType shouldn't have public constructor, just an internal one, is there any way to Enforce that using ControllerBase ? TType不应只有公共构造函数, TType应是内部构造函数,有没有办法使用ControllerBase来强制执行该构造函数?

  • TType must be an concrete class (Didn't include New() as a generic constrain since the constructors should be marked as Internal) TType必须是一个具体的类(由于构造函数应标记为Internal,因此不包含New()作为通用约束)

There is a way to enforce TType being a concrete class and forbidding constructor success at the same time. 有一种方法可以将TType强制为具体类,并同时禁止构造函数成功。 I guess it might be possible to try to instantiate TType, which will succeed only if it is a concrete type, however, you want to avoid instantiation. 我想也许可以尝试实例化TType,只有当它是具体类型时才能成功,但是,您要避免实例化。 I would suggest trying to throw an exception from the constructor. 我建议尝试从构造函数中引发异常。 In your controller base, you can surround the instantiation with exception handling code. 在您的控制器库中,您可以在实例化周围加上异常处理代码。 This will get through compile time only if you instantiate concrete type and it will get through runtime if you throw an exception... This is overall bad practice (if possible) and I guess you need totally different design to achive what are you looking for. 仅当实例化具体类型时,它才会通过编译时;如果引发异常,则它将通过运行时...这是总体上的坏习惯(如果可能的话),我想您需要完全不同的设计才能达到您的期望。

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

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