I've a problem in C# with a generic class:
class Hop<T>
{
static string x;
}
Can I initialize x
for all the instanc开发者_如何学JAVAe of Hop
?
Something like Hop.x = "test";
doesn't work for instance.
The problem is, there is no Hop
type, there is a Hop<T>
generic type. How about:
class Hop
{
static string X;
}
class Hop<T> : Hop
{
}
But the problem you still have, is this:
Hop<string>.X = "hello";
string x = Hop<int>.X; // x == "hello".
The static field is for the Hop
type, not the Hop<T>
type.
If you need compile-time initialization, you can write:
class Hop<T>
{
static string x = "Foo";
}
For more complicated initialization, you can use a class initializer:
class Hop<T>
{
static string x;
static Hop()
{
x = "Foo";
}
}
精彩评论