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

后端 未结 4 2026
半阙折子戏
半阙折子戏 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:53

    No, it is not. Generic types can be "open" or "closed." An open type is one like List where the type parameter isn't defined; List is a closed type.

    Essentially, the open type isn't treated as a proper "Type" by the runtime - only the closed versions are true types. So, MyGeneric and MyGeneric are two entirely different types, and thus have their own instances of the static variable.

    This is made more obvious by the fact that you can't call your static member in the way you suggest: MyGeneric.Variable will not compile in C#.

    This console application code illustrates it quite simply:

    class Program
    {
        static void Main(string[] args)
        {
            Test.i = 2;
            Test.i = 8;
    
            Console.WriteLine(Test.i);   // would write "8" if the fields were shared
            Console.WriteLine(Test.i);
            // Console.WriteLine(Test.i); // does not compile
            // Console.WriteLine(Test<>.i); // does not compile
        }
    }
    
    class Test
    {
        public static int i;
    }
    

提交回复
热议问题