C#
 Computer >> コンピューター >  >> プログラミング >> C#

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

  1. C#のクラスのメンバー関数とは何ですか?

    クラスのメンバー関数は、他の変数と同様に、クラス定義内にその定義またはプロトタイプを持つ関数です。メンバーであるクラスのオブジェクトを操作し、そのオブジェクトのクラスのすべてのメンバーにアクセスできます。 以下はメンバー関数の例です- public void setLength( double len ) {    length = len; } public void setBreadth( double bre ) {    breadth = bre; } 以下は、C#でメンバー関数にアクセスする方法を示す例です。 例 using System

  2. Pythonディクショナリビューオブジェクトとは何ですか?

    ディクショナリメソッドitems()、keys()、values()はビューオブジェクトを返します。 items()メソッドは、ディクショナリ内のキーと値のペアのリストを含むdict_itemsオブジェクトを返します >>> D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5} >>> i=D1.items() >>> i dict_items([('pen&