Skip to main content
 首页 » 编程设计

c#之基类中的虚拟方法使用子类中的静态变量

2024年02月13日11dyllove98

基类中的虚拟方法是否可以引用/访问/使用子类中的静态变量?

用代码解释可能更容易。在下面的示例中,是否可以使虚方法 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?? 
} 

请您参考如下方法:

Is it possible for a Virtual Method in a Base class to reference/access/use a Static variable from a child class?

没有。即使抛开事物的静态方面,您也在尝试访问变量,就好像变量是多态的一样。他们不是。

最简单的方法是创建一个抽象虚拟属性,并在每个方法中覆盖它。然后你在基类中的具体方法(可能根本不需要是虚拟的)可以调用抽象属性。

或者,如果您不介意每个实例都有一个字段,只需让您的基类构造函数在构造函数中使用分隔符进行拆分,并将其存储在基类声明的字段中:

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 - 我只是检查该行是否以给定的前缀开头。