具有实例计数器的BaseClass

时间:2018-10-18 08:03:27

标签: c#

我有一个基类和几个派生类(例如BaseChildA : Base)。每次我创建ChildA类的实例时,我都希望为其分配一个唯一的实例号(类似于关系数据库中的自动增量ID,但对于我的类而不是数据库中的内存)。

我的问题类似于this one,但有一个明显的区别:我希望基类自动处理此问题。对于我的每个派生类(ChildA,ChildB,ChildC等),我希望基类维护一个单独的计数,并在创建该派生类的新实例时对该计数进行递增。

因此,我的Base类中保存的信息可能最终看起来像这样:

ChildA,5
ChildB,6
ChildC,9

如果我随后实例化一个新的ChildB(var instance = new ChildB();),我希望为ChildB分配ID 7,因为它是从6开始的。

然后,如果我实例化一个新的ChildA,则希望为ChildA分配ID 6。

-

如何在Base类的构造函数中处理此问题?

2 个答案:

答案 0 :(得分:6)

您可以在基类中使用静态if [ -s ${file1} ] && [ -s ${file2} ] && [ -s ${file3} ]; then if [[ -s ${file1} && -s ${file2} && -s ${file3} ]]; then ,您可以在基类中按类型跟踪派生实例。由于if [[ -s ${file1} && -s ${file2} && -s ${file3} ]]; then echo "present" echo "Perform analysis" else echo "not present"; stat --printf="Value of file1: %s" "$file1" stat --printf="Value of file2: %s" "$file2" stat --printf="Value of file3: %s" "$file3" echo "skip"; fi 属于派生类型,因此您可以将Dictionary<Type, int>用作字典中的键。

this

输出:

this.GetType()

为了线程安全,可以使用class Base { static Dictionary<Type, int> counters = new Dictionary<Type, int>(); public Base() { if (!counters.ContainsKey(this.GetType())) counters.Add(this.GetType(), 1); else counters[this.GetType()]++; Console.WriteLine(this.GetType() + " " + counters[this.GetType()]); } } class Derived : Base { } class Derived2 : Base { } public static void Main() { new Derived(); new Derived2(); new Derived(); } 代替Derived 1 Derived2 1 Derived 2

答案 1 :(得分:0)

或线程安全版本

public class BaseClass
{
   public static ConcurrentDictionary<Type,int> Counter = new ConcurrentDictionary<Type, int>();   
   public BaseClass() => Counter.AddOrUpdate(GetType(), 1, (type, i) => i + 1);
}

用法

for (int i = 0; i < 2; i++)
   Console.WriteLine("Creating " + new A());

for (int i = 0; i < 4; i++)
   Console.WriteLine("Creating " + new B());

for (int i = 0; i < 1; i++)
   Console.WriteLine("Creating " + new C());

foreach (var item in BaseClass.Counter.Keys)
   Console.WriteLine(item + " " + BaseClass.Counter[item] );

输出

Creating ConsoleApp8.A
Creating ConsoleApp8.A
Creating ConsoleApp8.B
Creating ConsoleApp8.B
Creating ConsoleApp8.B
Creating ConsoleApp8.B
Creating ConsoleApp8.C
ConsoleApp8.A 2
ConsoleApp8.C 1
ConsoleApp8.B 4

Full Threaded Demo Here