C# 中類的使用


其實在C#和C++中類的使用基本相同,所以這里是C# 中類的使用小例子

using System;

namespace ConsoleApp2
{
    


            class Rectangle
        {
            //成員變量
            public double length, width;

            public double GetArea()
            {
                return length * width;
            }

            public void Display()
            {
                Console.WriteLine("長度:{0}", length);
                Console.WriteLine("寬度:{0}",width);
                Console.Write("面積:{0}",GetArea());

            }

        }
    //Rectangle 類結束
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.length = 4.5;
            r.width = 3.8;
            r.Display();

        }
    }

}

參考連接:

https://www.runoob.com/csharp/csharp-encapsulation.html

 

當類的屬性為 private時 就不可以在類的外部使用了,如果使用就會報錯

 

 

使用private屬性的變量

using System;

namespace ConsoleApp2
{
    


            class Rectangle
        {
            //成員變量
            private double length, width;

            public void acceptDetails()
            {
                Console.WriteLine("請輸入長度:");
                length = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("請輸入寬度");
                width = Convert.ToDouble(Console.ReadLine());

            }
            public double GetArea()
            {
                return length * width;
            }

            public void Display()
            {
                Console.WriteLine("長度:{0}", length);
                Console.WriteLine("寬度:{0}",width);
                Console.Write("面積:{0}",GetArea());

            }

        }
    //Rectangle 類結束
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.acceptDetails();
            r.Display();

        }
    }

}

運行結果:

請輸入長度:
12
請輸入寬度
12
長度:12
寬度:12
面積:144

 


免責聲明!

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



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