我的 child class 如何与妈妈 class 共享 idCounter?

How can my child class share idCounter with mother class?

我是编程的新手,我无法通过谷歌搜索找到我的问题的确切答案,所以希望我会尽可能简单易懂。

我的 public class MotherClass()public int Id 应该显示当前数字存储在 public static int idCounter 中。我想在我的 public class ChildClass : MotherClass.

中使用相同的 idCounter

所以当我为前任做准备时。 2 new MotherClass() objects 并假设 2 new ChildClass() objects,它们的 ID 应该是:1,2,3,4(共享)而不像 1,2 和 1,2(每个 class).

的不同计数器

这是我的:

public class MotherClass(){
    public static int idCounter {get; set;}
    public int Id { get; set; }
    public string Name { get; set; }

    static MotherClass(){
       idCounter = 1;
    }

   public MotherClass(string name, int id = -1){
   
     if(id == -1)
       Id = idCounter++;
     Name = name;
   }


public class ChildClass : MotherClass{
   
   public double Price { get; set; }

   public ChildClass(string name, double price int id =-1) : base(name,id){
     
      Price = price;

   }

}

这是您可以做到的一种方法:

public class MotherClass
{
    public static int IdCounter { get; private set; } = 1;
    public int Id { get; } = IdCounter++;
}

public class ChildClass : MotherClass { }

每次创建新的 MotherClassChildClass 时,IdCounter 都会递增。

示例:

Console.WriteLine(new MotherClass().Id); // 1
Console.WriteLine(new MotherClass().Id); // 2
Console.WriteLine(new ChildClass().Id);  // 3

您应该将 IdCounter 的 setter 设为私有,然后其他 类 无法修改该值。