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

标签 c# inheritance static polymorphism

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

用代码解释可能更容易。在下面的示例中,是否可以使虚方法 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 - 我只是检查该行是否以给定的前缀开头。

关于c# - 基类中的虚拟方法使用子类中的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20600451/

相关文章:

c# - MySql 在更新时添加值(value)

c# - C#中的构造函数和继承问题

javascript - 无法创建由继承自多个类的类组成的 AngularJS 服务

c# - 为什么是 "Do not access a static member that is defined in a base class from a derived class."

c# - 在非静态方法中使用静态成员会导致内存泄漏吗?

c# - 像网页一样在 C# 中发送 POST 请求?

c# - 转换分割字符串时出错

Java 错误 : Cannot make a static reference to the non-static method

c# - 获取对类的引用并仅从字符串值执行静态方法?

c# - 匹配 SomeWord_SomeSecondWord_SomeThirdWord 的正则表达式