Base类中的虚方法是否可以引用/访问/使用子类中的Static变量?
它可能更容易在代码中解释。在以下示例中,是否可以使虚拟方法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??
}
答案 0 :(得分:4)
Base类中的虚方法是否可以引用/访问/使用子类中的Static变量?
没有。即使除了静态方面,你也试图访问一个变量,好像变量是多态的一样。他们不是。
最简单的方法是创建一个抽象的虚拟属性,并在每个方法中覆盖它。然后基类中的具体方法(可能根本不需要是虚拟的)可以调用抽象属性。
或者,如果您不介意每个实例都有一个字段,只需让您的基类构造函数在构造函数中使用分隔符进行拆分,并将其存储在基类声明的字段中:
public class Base
{
private readonly string delimiter;
protected Base(string delimiter)
{
this.delimiter = delimiter;
}
// Quite possibly no need for this to be virtual at all
public void ParseFile(string fileContents)
{
string my3dPoints = fileContents.Split(delimiter)[1];
}
}
顺便说一句,我不确定在这种情况下我会使用Split
给出你的数据文件 - 我只是检查一行是否以给定的前缀开头。