I have a question regarding the following code:
abstract class a
{
public static string x;
}
class b<c> where c : a
{
public void f()
{
c.x=10;
}
}
This code does not compile. I get an error at the statement c.x=10; . The problem makes it look as if the condition where c:a does not have any effect at all.Can someone please explain why this is an error? Is it not true that x is shared as a static member by all children of a? And is there a way to circumvent this problem?
What I am trying to achieve is this : i have a subclass of a, all of whose objects share a common property and this property has to be set through f() in the generic class b. Is it alright if i replace the statement in question with a.x=10? If not, how is a.x different from c.x (or h.x where h is the subclass of a)?
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
you can access
P.XthroughP.XorQ.XorR.Xbut it’s still the same field:As you’ve discovered, you can’t do this with generic type parameters. But accessing
Xthough the type parameter doesn’t really make a lot of sense, because all you change isP.Xwhich 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
Aand want all instances of types that derive fromAto have a certain property, you can define this: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:
What about this?
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.