C# 中的物件是什麼?


與其他面嚮物件語言一樣,C# 也有物件和類。物件是現實世界實體以及類的一個例項。使用物件訪問類的成員。

要訪問類成員,你需要在物件名稱後使用點 (.) 運算子。點運算子將物件名稱與成員名稱關聯起來,例如,

Box b1 = new Box();

上面,你可以看到 Box1 是我們的物件。我們將使用它訪問成員 −

b1.height = 7.0;

你也可以使用它來呼叫成員函式 −

b1.getVolume();

以下是一個示例,展示了物件和類在 C# 中是如何工作的 −

示例

 實際演示

using System;

namespace BoxApplication {
   class Box {
      private double length; // Length of a box
      private double breadth; // Breadth of a box
      private double height; // Height of a box

      public void setLength( double len ) {
         length = len;
      }

      public void setBreadth( double bre ) {
         breadth = bre;
      }

      public void setHeight( double hei ) {
         height = hei;
      }

      public double getVolume() {
         return length * breadth * height;
      }
   }

   class Boxtester {
      static void Main(string[] args) {
         // Creating two objects
         Box Box1 = new Box(); // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;

         // using objects to call the member functions
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         Console.ReadKey();
      }
   }
}

輸出

Volume of Box1 : 210
Volume of Box2 : 1560

更新於: 20-6 月 -2020

1000+ 次檢視

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.