C#構造方法(構造函數)


構造方法特點:

一 ,與類同名

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);
        }
    }

二,沒有帶返回值

三 ,無參構造函數

        public Product()  //無參
        {
            ID = 1100;
            NAME = "手機";
            Price = 8888;
            type = ProductType.手機;
            Birthday = new DateTime(2019, 11, 1);
        }

四,有參構造函數,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);

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM