從 C# 中的另一個建構函式呼叫建構函式

從 C# 中的另一個建構函式呼叫建構函式

本教程將討論在 C# 中從同一個類的另一個建構函式呼叫一個建構函式的方法。

在 C# 中使用 this 關鍵字從同一個類的另一個建構函式呼叫一個建構函式

如果我們的類有多個建構函式,而我們又想從另一個建構函式呼叫一個建構函式,則可以在 C# 中使用 this 關鍵字。this 關鍵字是對 C# 中當前類例項的引用。以下程式碼示例向我們展示瞭如何使用 C# 中的 this 關鍵字從同一個類的另一個建構函式呼叫一個類的一個建構函式。

using System;

namespace call_another_constructor {
  class sample {
    public sample() {
      Console.WriteLine("Constructor 1");
    }
    public sample(int x) : this() {
      Console.WriteLine("Constructor 2, value: {0}", x);
    }
    public sample(int x, int y) : this(x) {
      Console.WriteLine("Constructor 3, value1: {0} value2: {1}", x, y);
    }
  }
  class Program {
    static void Main(string[] args) {
      sample s1 = new sample(12, 13);
    }
  }
}

輸出:

Constructor 1
Constructor 2, value: 12
Constructor 3, value1: 12 value2: 13

我們使用 3 個不同的建構函式建立了 sample 類。建構函式 sample(int x, int y) 呼叫建構函式 sample(int x),並將 x 作為引數傳遞給 x。然後,建構函式 sample(int x)this() 呼叫建構函式 sample()sample() 建構函式在 sample(int x) 建構函式之前執行,而 sample(int x) 建構函式在 sample(int x, int y) 建構函式之前執行。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相關文章 - Csharp Class