How to override method with derived return type in C#?

后端 未结 3 525
南旧
南旧 2021-01-25 20:28

I want to override a virtual method with a derived class type. What\'s the current best way to do this? So far I\'ve found two approaches:

  1. Use an abstract<
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 21:10

    The new keyword implicitly 'overrides' the base functionality anyway. Unless for some reason you specifically want override to appear in code, then a single new modifier will suffice. I would also explore abstrating the clone functionality into an interface, it allows you to make more assumptions in code, at a later date.

    public interface ICloneable
    {
        T Clone();
    }
    
    public class A1 : ICloneable
    {
        public int X1 { get; set; }
        public A1(int x1) { this.X1 = x1; }
    
        public virtual A1 Clone()
        {
            return new A1(X1);
        }
    }
    public class A2 : A1, ICloneable
    {
        public int X2 { get; set; }
    
        public A2(int x1, int x2)
            : base(x1)
        {
            this.X2 = x2;
        }
    
        public virtual new A2 Clone()
        {
            return new A2(X1, X2);
        }
    }
    
    public class A3 : A2, ICloneable
    {
        public int X3 { get; set; }
    
        public A3(int x1, int x2, int x3)
            : base(x1, x2)
        {
            this.X3 = x3;
        }
    
        public virtual new A3 Clone()
        {
            return new A3(X1, X2, X3);
        }
    }
    

    EDIT: The resultant possible behaviour:

    public class A4 : A3, ICloneable
    {
        public int X4 { get; set; }
    
        public A4(int x1, int x2, int x3, int x4)
            : base(x1, x2, x3)
        {
            this.X4 = x4;
        }
    
        public override A3 Clone()
        {
            return ((ICloneable)this).Clone();
        }
    
        A4 ICloneable.Clone()
        {
            return new A4(X1, X2, X3, X4);
        }
    }
    

提交回复
热议问题