Static variables are instance class variables?

Simple question:

Are static variables class instance variableor class variablegrounds?

Knowing that class instance variablethese are variables that are defined for each class and subclass where it is defined. And class variable- these are variables that are global for all subclasses where it is defined, including itself.

EDIT: Knowing that I'm choking on a lot of C # good guy, I use the term class instance as a class that has an instance of some MetaClass in it. This greatly simplified my question. Although it’s not entirely wrong to say that if you think that VM certainly has an artifact that represents the evrey class (containing the dictionay method, instance size, superclass, ...). Thanks

+3
source share
3 answers

They are class variables. In C #, there is nothing like an instance variable of the Smalltalk class. That is, there is no way to define a variable that is common to all instances of the class, but which has different meanings for its subclasses.

To get a “similar” behavior, but with the disadvantage that the var class instance is only available after creating an instance of your class, I did something like this:

public class BaseClass
{
    private static Dictionary<Type, object> ClassInstVarsDict = new Dictionary<Type, object>();

    public object ClassInstVar
    {
        get
        {
            object result;
            if (ClassInstVarsDict.TryGetValue(this.GetType(), out result))
                return result;
            else
                return null;
        }
        set
        {
            ClassInstVarsDict[this.GetType()] = value;
        }
    }
}

public class DerivedClass1 : BaseClass
{
}

public class DerivedClass2 : BaseClass
{
}
+1
source

Static variables "belong" to the type - they are not instance variables.

That is, they are distributed among all instances of the type, including common private constructed types.

, ThreadStatic, .

+9

, AppDomain. , ThreadStaticAttribute, .

, , , "" . .

:

class MyClass<T>
{
   public static string Name;
}

, MyClass<int> Name MyClass<string> .


, , ?

generics :

class Program
{
    static void Main(string[] args)
    {
        Derived1.WhatClassAmI = "Derived1";
        Derived2.WhatClassAmI = "Derived2";

        Console.WriteLine(Derived1.WhatClassAmI); // "Derived1"
        Console.WriteLine(Derived2.WhatClassAmI); // "Derived2"

        Console.WriteLine(BaseClass<Derived1>.WhatClassAmI); // "Derived1"
        Console.WriteLine(BaseClass<Derived2>.WhatClassAmI); // "Derived2"
        Console.Read();
    }

    class BaseClass<T> where T : BaseClass<T>
    {
        public static string WhatClassAmI = "BaseClass";
    }

    class Derived1 : BaseClass<Derived1>
    {
    }

    class Derived2 : BaseClass<Derived2>
    {
    }
}

They use the "same" static, but each of them has its own values ​​due to type closure.

+4
source

All Articles