Field belongs to a class, but how to use polymorph

2019-07-29 12:36发布

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)...

2条回答
Rolldiameter
2楼-- · 2019-07-29 13:13

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.

查看更多
我只想做你的唯一
3楼-- · 2019-07-29 13:21

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).

查看更多
登录 后发表回答