当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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 instance 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";
   }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: