简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM