Is it possible for a Virtual Method in a Base class to reference/access/use a Static variable from a child class?
Its probably easier to explain in code. In the following example is it possible to make the virtual method Arc::parseFile()
look for 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?
No. Even aside from the static side of things, you're trying to access a variable as if variables were polymorphic. They're not.
The simplest approach would be to make an abstract virtual property, and override it in each method. Then your concrete method in the base class (which may not need to be virtual at all) can call the abstract property.
Alternatively, if you don't mind having a field per instance, just make your base class constructor take a delimiter to split on in the constructor, and store that in a field declared by the base 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];
}
}
As an aside, I'm not sure I'd use Split
in this case given you data file - I'd just check whether the line starts with the given prefix.
See more on this question at Stackoverflow