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