Overriding (cast)

后端 未结 2 788
心在旅途
心在旅途 2020-12-29 09:06

If I have a base class and two derived classes, and I want to implement the casting between the two derived classes by hand, is there any way to do that? (in C#)

<         


        
相关标签:
2条回答
  • 2020-12-29 09:51

    You must implement a explicit or implicit operator.

    class Imp_A : AbsBase
    {
       public static explicit operator Imp_B(Imp_A a)
       {
          Imp_B b = new Imp_B();
    
          // Do things with b
    
          return b;
       }
    }
    

    Now you can do the following.

    Imp_A a = new Imp_A();
    Imp_B b = (Imp_B) a;
    
    0 讨论(0)
  • 2020-12-29 10:07

    I'd suggest you write Imp_B like this, if possible:

    class Imp_B : Imp_A
    {
        private int A;
        private int B;
        private int C;
        private int D;
        private int lastE { get { return this.E.Last(); } }
    }
    

    If you can't actually derive from ImpB, it's impossible for you to "treat" a ImpA object as an ImpB transparently the way you'd like, because they just aren't the same thing in memory. So, implement an explicit conversion.

    0 讨论(0)
提交回复
热议问题