基类中的虚方法是否可以引用/访问/使用来自子类的静态变量?基类中的虚方法使用子类中的静态变量
它可能更容易在代码中解释。在以下示例中,可以使虚拟方法Arc::parseFile()
查找data_arc
?
public class Base {
public static string DATA_3D = "data_3d";
public virtual void parseFile(string fileContents) {
// Example of file contents: "data_3d (0,0,0),(1,1,1),(2,2,2)
// Example of file contents: "data_arc (0,0,0),(1,1,1),(2,2,2)
// Example of file contents: "data_point (0,0,0)
string my3dPoints = fileContents.Split(DATA_3D)[1];
}
}
public class Arc : Base {
public static string DATA_3D = "data_arc";
// Will the base method parseFile() correctly look for "data_arc"
// and NOT data_3d??
}
这真的不是一个好主意。为什么不添加虚拟getter方法并将静态字符串值分配给类构造函数中的数据成员? – OldProgrammer
@OldProgrammer我之所以这样做是因为如果它能够工作,那将是一个非常优雅和简单的解决方案。只需要更改1个变量值(静态变量),并且解析函数将适用于所有类型的字符串(一系列顶点)。 –
您是否注意到隐藏'Base'字段中的'Arc'字段的警告?隐藏基类中的成员永远不是一个好主意。你想要一个'虚拟'只能获取属性。不幸的是,它不能是'static',但'get'访问器返回的值在任何意义上都可以是常量或“静态”的。 –