C# 類 屬性 概念


類屬性

初學C#,對許多概念不甚了解,就比如這個屬性,做個筆記

C#中“屬性”概念是類字段的訪問器(getter/setter)

using System;

namespace Hello 
{
    class Shape
    {
        // 兩個私有成員變量(字段)
        private int _width;
        private int _height;
		
        // 定義了width屬性,其包含了對_width字段的getter和setter
        public int width
        {
            // 這里的value是默認隱含的參數
            set { this._width = value; }
            get { return this._width; }
        }
        
        public int height
        {
            set { this._height = value; }
            get { return this._height; }
        }

        public int square()
        {
            return this._width * this._height;
        }
        
        
    }
    public class Program 
    {
        public static void Main()
        {
            Shape shape = new Shape();
            
            // 此處賦值操作的10就是width屬性中setter的隱含參數value
            shape.width = 10;
            shape.height = 20;
            Console.WriteLine("{0}", shape.square());
            
            shape.width = 30;
            shape.height = 40;
            Console.WriteLine("{0}", shape.square());
        }
    }
}


免責聲明!

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



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