1. 程式人生 > 其它 >C# set 與get 的一般應用

C# set 與get 的一般應用

namespace 屬性Set與Get
{
    class Program
    {
        static void Main(string[] args)
        {
            EmployeeInformation emp = new EmployeeInformation();//建立物件
            //以下是對欄位的一般性賦值:
            emp._name = "張三";
            emp.Age =38;//此處用屬做了限制,如果輸入了不恰當的年齡(如:-38歲),預設設定成18
            emp.Gender = '
';//此處用屬做了限制,如果輸入了不恰當的性別,預設設定成男 emp._department = "業務部"; emp._position = "總經理"; emp.OutInformation();//輸出結果 Console.ReadKey(); } } //類中可以存放的成員:欄位,屬性,方法 public class EmployeeInformation { public string _name; private
int _age; private char _gender; public string _department; public string _position; //屬性是用於限制使用者輸入輸入格式 public int Age { get { return _age; } set {
if (value < 0)//如果輸入的年齡小於0就設定一個預設18 { _age = 18; } else { _age = value; } } } public char Gender { get { return _gender; } set { if (value != '' && value != '')//如果輸入的性別不是男和女,預設設定為男 { _gender = ''; } else { _gender = value; } } } public void OutInformation() { Console.WriteLine("名字:{0},年齡:{1}歲,性別:{2},部門:{3},職位:{4}。",this._name,this._age,this._gender,this._department,this._position); } } }