Best way to refer to my own type

前端 未结 5 1868
轻奢々
轻奢々 2021-01-03 06:02
abstract class A where T:A
{
    public event Action Event1;
}

class B : A
{
    //has a field called Action Event1;
}
         


        
5条回答
  •  一生所求
    2021-01-03 06:23

    Since A is abstract, you can add abstract methods to A and invoke them from A and B, which will be forced to implement the method, will be the invoker:

    abstract class A where T:A
    {
        public event Action Event1;
        public abstract void Method();
    
        public A(){Method();}
    }
    
    class B : A
    {
        //has a field called Action Event1;
        public void Method(){ //stuff }
    }
    

    On instantiation of B, the base class constructor will call Method() which is only implemented in B, forcing B's instance to be called.

    This allows A to invoke subclass specific methods without requiring A to have specific knowledge of Children. The downside is that ALL children must implement Method or re-abstract it to their own children.

提交回复
热议问题