Use of properties

Topic description  

Use of properties. (console application)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Using the namespace attribute
{
    class Program
    {
        static void Main(string[] args)
        {
            //Instantiate the class, assign values ​​separately, and call the methods in it
            Clerk zsClerk = new Clerk();
            zsClerk._name = "Zhang San";
            zsClerk.Gender = '中';
            zsClerk.Age = -25;
            zsClerk._department = "Department of Manpower";
            zsClerk._workyear = 5;
            zsClerk.Write();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Using the namespace attribute
{
    class Clerk
    {
        public string _name;
        private char _gender;
        public char Gender
        {
            get
            {
                if(_gender!='male'||_gender!='female')
                    _gender ='man';
                return _gender;
            }
            set { _gender = value; }
        }
        private int _age;
        // Usually get, set are called accessors
        // There are four types of properties
        // both read and write
        //read only contains get
        //write only contains set only
        //Auto property get; set
        public int Age
        {
            get//get can be used to limit the value
            { return _age; }
            set//set can be used to qualify assignments
            {
                if (value < 0 || value > 120)
                    value = 0;
                    _age = value;
            }
        }
        //After having attributes, we often access fields through attributes
        //Properties are usually declared as public and fields are declared as private
        //Accessing the fields in the class externally is achieved through attributes
        public string _department;
        public int _workyear;
        public void Write()
        {
            Console.WriteLine("My name is {0}, I am from {1}, I am {2} years old this year, I work for {3} and have been working for {4} years", this._name, this.Gender, this.Age, this._department, this._workyear);
        }
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325956004&siteId=291194637