当前位置:网站首页>Learning record -- memo on constructors and attributes in C

Learning record -- memo on constructors and attributes in C

2022-06-23 02:52:00 MrLi001

First, there are two classes , Respectively Program Classes and Customer Class as a reference . among Program Store the main function in , Customer Stored in class customer Properties of .

Customer Class

class Customer
    {
        private string name;
        public string address;
        private int age;
        private string creatTime;
    }

stay Program Instantiation in Customer Class object

Stabilization mode ① Constructors , All attributes

Customer Constructors

public Customer(string name, string address, int age, string creatTime)// Constructors , It can be understood as written initialization 
        {
            this.name = name;
            this.address = address;
            this.age = age;
            this.creatTime = creatTime;
        }

stay Program In the implementation of

class Program
    {
        static void Main(string[] args)
        {
            Customer cusm = new Customer(" Li Si "," Here, there ",55,"2000");
           
        }
    }

Stabilization mode ②( For attribute )

Customer Medium set、get Method , With age Attribute as an example

public void SetAge(int age)
{
    this.age = age;//this.age Represents the... Defined in this class , hinder age Represents the parameters in this method 
}
public int GetAge()
{
    return age;
}

stay Program In the implementation of

class Program
    {
        static void Main(string[] args)
        {
            Customer cusm = new Customer(" Li Si "," Here, there ",55,"2000");
            cusm.SetAge(8);
        }
    }

Stabilization mode ③( For attribute )

Customer Medium set、get Method simple version , With age Attribute as an example

public int Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
            }
        }

stay Program In the implementation of

class Program
    {
        static void Main(string[] args)
        {
            Customer cusm = new Customer(" Li Si "," Here, there ",55,"2000");
            cusm.Age=18;
        }
    }

④ For Customer Properties not defined in , You can create attributes directly and automatically

public string Detail { get; set; }

stay Program In the implementation of

class Program
    {
        static void Main(string[] args)
        {
            Customer cusm = new Customer(" Li Si "," Here, there ",55,"2000");
            cusm.Detail = " Here are the details about Li Si ";
        }
    }
原网站

版权声明
本文为[MrLi001]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201271735251709.html