Field belongs to a class, but how to use polymorph

2019-07-29 12:21发布

问题:

I have a method in a base class

class Base
{
   private static string Colour = "blue";
   string DoStuff() { return ColourProp; }

   protected virtual string ColourProp { get{ return Base.Colour; } }
}

that is called on an instance of this subclass

class Sub
{
   private static string Colour = "orange";

   protected override string ColourProp { get{ return Sub.Colour; } }
}

At the moment I'm using virtual properties, is this the only way? (considering that fields cannot be virtual)...

回答1:

Yes, you do need to use either a virtual property or a virtual method to accomplish this. The CLR will dynamically dispatch all calls to ColourProp correctly based on the type of the object (i.e. polymorphism).



回答2:

This looks totally fine. Don't worry about virtual properties. This provides not only an encapsulation of your data against other objects but also against subclasses.