Static members are not inherited, although it's confusingly possible to access a static member through a derived type. For example, in the following code
class P
{
public static string X;
}
class Q : P { }
class R : P { }
you can access P.X
through P.X
or Q.X
or R.X
but it's still the same field:
P.X = "Hello";
Q.X = "World";
Console.WriteLine(R.X); // prints "World"
As you've discovered, you can't do this with generic type parameters. But accessing X
though the type parameter doesn't really make a lot of sense, because all you change is P.X
which you write directly without the generic type parameter.
I'm not really sure what you're trying to achieve. If you have an abstract class A
and want all instances of types that derive from A
to have a certain property, you can define this:
abstract class A
{
public abstract string X
{
get;
}
}
class A1 : A
{
public override string X
{
get { return "A1"; }
}
}
class A2 : A
{
public override string X
{
get { return "A2"; }
}
}
If you want to associate a bit of information with a type (not instance), you can define a static field that is parameterized with a type using a generic class:
class Info<T>
{
public static string X;
}
Info<A1>.X = "Hello";
Info<A2>.X = "World";
Console.WriteLine(Info<A1>.X); // prints "Hello"
Console.WriteLine(Info<A2>.X); // prints "World"
What about this?
abstract class Job
{
public abstract string ExePath
{
get;
}
public void Execute(string[] args)
{
Console.WriteLine("Executing {0}", this.ExePath);
}
}
abstract class Job<T> where T : Job<T>
{
public override string ExePath
{
get { return JobInfo<T>.ExePath; }
}
}
class ConcreteJob1 : Job<ConcreteJob1> { }
class ConcreteJob2 : Job<ConcreteJob1> { }
static class JobInfo<T> where T : Job<T>
{
public static string ExePath;
}
static class JobInfoInitializer
{
public static void InitializeExePaths()
{
JobInfo<ConcreteJob1>.ExePath = "calc.exe";
JobInfo<ConcreteJob2>.ExePath = "notepad.exe";
}
}
This matches closely the process you describe in your comment. It should work, although it's not how I would design a configurable Job model.