开发者

How to initialize a static attribute in a generic class?

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";
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜