Are static members of generic classes shared betwe

2019-02-16 05:10发布

I'm trying to create a generic class which will have some static functions based on the type. Are there static members for each type? Or only where there is a generic used? The reason I ask is I want a lock object for each type, not one shared between them.

So if I had

class MyClass<T> where T:class
{
    static object LockObj = new object();
    static List<T> ObjList = new List<T>();
}

I understand that ObjList would definitely have a different object created for each generic type used, but would the LockObj be different between each generic instantiation (MyClass<RefTypeA> and MyClass<RefTypeB>) or the same?

3条回答
相关推荐>>
2楼-- · 2019-02-16 05:39

Instantiated generic types in C# are actually different types at runtime, hence the static members will not be shared.

查看更多
相关推荐>>
3楼-- · 2019-02-16 05:42

It will be different for each T. Basically, for all different T you will have different type and members are not shared between different types.

查看更多
Evening l夕情丶
4楼-- · 2019-02-16 05:43

Just check for yourself!

public class Static<T>
{
    public static int Number { get; set; }
}

static void Main(string[] args)
{
    Static<int>.Number = 1;
    Static<double>.Number = 2;
    Console.WriteLine(Static<int>.Number + "," + Static<double>.Number);
}
// Prints 1, 2
查看更多
登录 后发表回答