简体   繁体   中英

Override property of the base class with a derived class

In a C# code, if the Rebar class derives from Reinforcement class and the RebarShape class inherits the ReinforcementShape class. Is it possible to override the property ReinforcementShape in the base class with the RebarShape class?

   public class ReinforcementShape
   {
   }

   public class RebarShape : ReinforcementShape
   {
   }

   public class Reinforcement
   {
        public ReinforcementShape Shape { get; set; }
   }


   public class Rebar : Reinforement
   {
        // I want to override the Shape property
        // but with its derived class which is RebarShape

        // override the base property somehow!
        public RebarShape Shape { get; set; }
   }

Update:

What is wrong with the current implementation?

In base:

public virtual ReinforcementShape Shape { get; set; }

In derived:

public new RebarShape Shape { get; set; }

You can do this with generics, no need to override the base-class member:

public class Reinforcement<T> where T: ReinforcementShape 
{
    public <T> Shape { get; set; }
}

public class Rebar : Reinforement<RebarShape>
{
}

Now you can easily create an instance of ReBar and access its Shape -property which is an instance of RebarShape :

var r = new Rebar();
r.Shape = new RebarShape();

An attemp to assign an instance of ReinforcementShape to that property will cause a compile-time error, only a RebarShape is valid at this point.

EDIT: as per your edit. You can only override a member by overriding it´s implementation, not it´s return-value. So using virtual won´t do anything in your case. However as R.Rusev already mentioned you only need the new -keyword on your derived member, which will actually provide a completely new member which has the same name as that one from your base-class. But actually it is a completely different member which thas nothing in common with the former one. However when you write the following

Reinforcement r = new Rebar();
// assign value to Shape
var shape = r.Shape;

the original implemenation is used, not your neew one. So shape would be of type ReinforcementShape instead of RebarShape . The only way around this is to declare r as Rebar in the first place:

Rebar r = new Rebar();
// assign value to Shape
var shape = r.Shape;

But this is quite confusing to any user of your application and maybe to yourself also. I´d generelly not recommend to use that keyword. Better use the first approach.

You can use the new keyword to do it. So your definition of Rebar class will look like this.

public class Rebar : Reinforement
{
    public new RebarShape Shape
    {
        get { return (RebarShape)base.Shape; }
        set { base.Shape = value; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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