当我们创建一个对象时,将 1 增加到变量

本文关键字:增加 变量 我们 创建 一个对象 | 更新日期: 2023-09-27 17:57:12

嘿,我

正在创建一个已使用的程序,我试图使构造函数共享值,但它不会创建一个名为(已使用)的包含实例变量的类:名称字符串 ;数字 int ;算 int 他的 instanse 是 120 ;创建属性该集合并获取名称和原产获取计数*对于每个创建对象,我们增加 1 进行计数

public class employed //creating class
    { // creating instanse variable 
        private string name;
        private  int number;
        private static int count; //declare it as a static so we can use it in a static method
        public string proparaty
        {
            set
            { name = value; }
            get { return name; } 
        }
        public int propartyForCount
        {
            get
            {
                return count;
            }
        }
       static employed() { // we make it static so we can share the value 
           count = 120;
           count++;
        }
    }
    static void Main(string[] args)
    {
        employed c1 = new employed();
        employed c2 = new employed();
        employed c3 = new employed(); 
        Console.Write("the count number is {0} ", c1.propartyForCount);
    } 

当我们创建一个对象时,将 1 增加到变量

静态构造函数只对类型执行一次(在第一次使用类型之前)。从 MSDN:

自动调用静态构造函数来初始化类 在创建第一个实例或任何静态成员之前 引用。

因此,您只会count增加一次。

如果你想在每次实例化新员工时增加这个变量,那么你应该在实例构造函数中这样做:

private static int count = 120;
public employed() 
{
    count++;
}