Is a static member variable common for all C# generic instantiations?

后端 未结 4 2024
半阙折子戏
半阙折子戏 2020-12-11 15:11

In C# I have a generic class:

public class MyGeneric where ParameterClass: MyGenericParameterClass, new() {
    public static int Varia         


        
4条回答
  •  执笔经年
    2020-12-11 15:56

    Section 25.1.4 of the ECMA C# Language specification

    A static variable in a generic class declaration is shared amongst all instances of the same closed constructed type (§26.5.2), but is not shared amongst instances of different closed constructed types. These rules apply regardless of whether the type of the static variable involves any type parameters or not.

    You may see this blog post: Static fields in generic classes by Gus Perez

    You can't do that in C# as well.

    MyGeneric.Variable = 1;
    

    Consider the following example from ECMA Language Specification.

    class C
    {
        static int count = 0;
        public C()
        {
            count++;
        }
        public static int Count
        {
            get { return count; }
        }
    }
    class Application
    {
        static void Main()
        {
            C x1 = new C();
            Console.WriteLine(C.Count);  // Prints 1 
            C x2 = new C();
            Console.WriteLine(C.Count); // Prints 1 
            Console.WriteLine(C.Count);  // Prints 1 
            C x3 = new C();
            Console.WriteLine(C.Count);  // Prints 2 
        }
    }
    

提交回复
热议问题