字段属于一类,但是如何使用多态 [英] Field belongs to a class, but how to use polymorphism
本文介绍了字段属于一类,但是如何使用多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在基类中有一个方法
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)...
推荐答案
是的,您确实需要使用虚拟属性或虚拟方法来完成此任务. CLR将根据对象的类型(即多态性)正确地动态调度对ColourProp
的所有调用.
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).
这篇关于字段属于一类,但是如何使用多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文