Generic classes and static fields

血红的双手。 提交于 2020-01-03 17:16:14

问题


Is there a way to share one static variable between several different generic classes ?

I have a class

class ClassA <T> : ObservableCollection<T> {

    static int counter;

    //...
}

and a couple of instances of it with different parameter instantiations, like

ClassA<int> a = new ClassA<int>();
ClassA<double> b = new ClassA<double>();
ClassA<float> c = new ClassA<float>();

Is there a way that the instances a, b, and c share the static field counter ?

Any answers and comments are pretty much appreciated :)


回答1:


You could wrap the counter in it's own singleton class, then reference the counter class from A, B, and C.




回答2:


Static fields are dependent upon their class (this is how C# handles telling which static members are which), and when you pass in a different generic type you're effectively defining a separate class.

So, no. Something like a shared counter would probably be better handled by whatever class is calling the Thing That Counts, since it's that's class that'll be most interested in the state of that counter anyway. If you can't do this for whatever reason (this class is being referenced by a bunch of unrelated threads), then you can make a static class to hold the state of the library, but this causes problems with testability so I'd try to avoid it if you can.




回答3:


The simplest solution:

    class Program
{
    static void Main(string[] args)
    {
        ClassA<int> a = new ClassA<int>();
        ClassA<double> b = new ClassA<double>();
        Console.WriteLine(a.GetCounterAndAddOne());
        Console.WriteLine(b.GetCounterAndAddOne());
        Console.Read();
    }
}

class BaseA
{
    protected static int counter = 0;
}

 class ClassA<T>:BaseA
{
     public int GetCounterAndAddOne()
     {
         return BaseA.counter++;
     }
}

firsr call to GetCounterAndAddOne prints 0, the second 1, and it will go on as needed



来源:https://stackoverflow.com/questions/10985560/generic-classes-and-static-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!