一.C#中的构造函数
特点:1.构造函数具有和类一样的名称;
- 构造函数没有返回值,也不能用void修饰,只有访问修饰符。
- 构造函数是在实例化类时最先执行的方法,通过这个特性可以给对象赋初值。
- 每个类中都会一个构造函数,如果用户定义的类中没有显式的定义任何构造函数,
编译器就会自动为该类型生成默认构造函数,类里面没有构造函数也可以,系统会为你自动创建无参构造函数。
例:class test //test类 构造函数,目的是用于初始化类。比如你定义了一个类A |
- 无参的构造函数
public class Product//类 { public int ID { get; set; } public String NAME { get; set; } public Decimal Price { get; set; } public ProductType type { get; set; } public DateTime Birthday { get; set; } public Product() //方法 无参 { ID = 1100; NAME = "手机"; Price = 8888; type = ProductType.手机; Birthday = new DateTime(2019, 11, 1); } } |
2.有参构造函数,this当前对象
public Product(int id,string Name,int price, ProductType type) { this.ID = id; this.NAME = Name; this.Price = price; //this当前对象 } |
Product s1 = new Product();//无参 Product s2 = new Product("2000","huawie", 5000,ProductType.服装, new DateTime(2019,2,3)); //有参 Console.WriteLine(s2.ID+s2.NAME+s2.Price+ProductType.服装); Console.ReadLine(); Console.WriteLine(s1.ID); |
2.强制使用有参构造方法