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

后端 未结 3 500
南旧
南旧 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条回答
  •  不思量自难忘°
    2021-01-25 21:15

    I'd advise against all of this. Just stick to the standard interfaces and patterns for such things. Implement System.ICloneable...

    http://msdn.microsoft.com/en-us/library/system.icloneable(v=vs.110).aspx

    Object Clone()
    

    Simple no?

    If you must deviate, I would use generics as Andrew Kennan has suggested. However I would still implement System.ICloneable as it makes the class more inter-operable with other frameworks.

    In addition ICloneable should be implemented using a protected constructor e.g.

    public class A1 : ICloneable
    {
        public A1(int x1) { this.X1 = x1; }
        protected A1(A1 copy) { this.X1 = copy.X1; }
    
        public int X1 { get; set; }
    
        public virtual object Clone()
        {
            return new A1(this); // Protected copy constructor
        }
    }
    

    This way you can inherit A1 as such...

    public class B1 : A1, ICloneable
    {
        public B1(int x1, int y1) : base(x1) { this.Y1 = y1; }
        protected B1(B1 copy) : base(copy) { this.Y1 = copy.Y1; }
    
        public int Y1 { get; set; }
    
        public virtual object Clone()
        {
            return new B1(this); // Protected copy constructor
        }
    }
    

提交回复
热议问题