ダミーの場合は、クラス/オブジェクト、フィールド、アクセス修飾子、プロパティ、コンストラクタ


このチュートリアルでは、プログラミングの背景や既存の知識があると仮定します.

クラス/オブジェクト


クラスはオブジェクトのテンプレートであり、オブジェクトはクラスのインスタンスです.オブジェクトはクラス内のエンティティです.colorclass carの対象である.
class Car 
{
  string color = "red";
}

C≠フィールド(変数)


クラス内で直接宣言された変数は、しばしばフィールド(または属性)と呼ばれます.

int myNum = 5;               // Integer (whole number)
double myDoubleNum = 5.99D;  // Floating point number
char myLetter = 'D';         // Character
bool myBool = true;          // Boolean
string myText = "Hello";     // String

アクセス修飾子


アクセス修飾子は、クラス、フィールド、メソッド、およびプロパティのアクセスレベル/可視性を設定するために使用されるキーワードです.
publicprivateprotected:あなたはおそらくあなたが神のレベルのステータスに到達しない限り、使用するものです😂.internal神のためです.

Cプロパティ


プロパティは、アクセス修飾子を持つフィールド(変数)、フィールドに“publicなど”を置く瞬間です.

class Car
{
  public string model;  // public
  private string year;   // private
  string type; // private

  // The `{set; get;}` means you can access and change the property.
  public string model {set; get;} // public
}

コンストラクタ


コンストラクタは、オブジェクトを初期化するのに使用される特別なメソッドです.

💡 A constructor is a method that gets called or runs when a class is created.
It can be used to set initial values for fields.
The constructor name must match the class name.
It cannot have a return type (like void or int).

All classes have constructors by default: if you do not create a class constructor yourself, C# creates one for you. However, then you are not able to set initial values for fields.


// Create a Car class
class Car
{
  public string model;  // Create a field

  // Create a class constructor for the Car class
  public Car()
  {
    model = "Mustang"; // Set the initial value for model
  }

  static void Main(string[] args)
  {
    Car Ford = new Car();  // Create an object of the Car Class (this will call the constructor)
    Console.WriteLine(Ford.model);  // Print the value of model
  }
}

// Outputs "Mustang"

コンストラクタ


コンストラクタはまた、フィールドを初期化するために使用されるパラメータを取ることができます.
class Car
{
  public string model;
  public string color;
  public int year;

  // Create a class constructor with single or multiple parameters
  public Car(string modelName, string modelColor, int modelYear)
  {
    model = modelName;
    color = modelColor;
    year = modelYear;
  }

  static void Main(string[] args)
  {
    Car Ford = new Car("Mustang", "Red", 1969);
    Console.WriteLine(Ford.color + " " + Ford.year + " " + Ford.model);
  }
}

// Outputs Red 1969 Mustang

参考文献


w3schools