在 C# 中從型別中建立新例項

Muhammad Maisam Abbas 2024年2月16日
在 C# 中從型別中建立新例項

本教程將討論使用 C# 在執行時建立給定資料型別的新例項的方法。

在 C# 中使用 Activator 類從型別建立新例項

如果我們想在執行時建立資料型別的新例項並且不知道資料型別,則可以使用 Activator 類和 Type 類來實現此目標。Activator提供了根據 C# 中的型別建立物件例項的方法。Activator.CreateInstance() 方法用於建立具有最適合 C# 中指定型別的建構函式的指定型別的例項。Type表示 C# 中的資料型別。在這種情況下,我們可以使用 Type 類來確定未知資料型別。下面的程式碼示例向我們展示瞭如何在執行時建立資料型別的新例項而又不使用 C# 中的 Activator 類和 Type 類來知道資料型別。

using System;

namespace new_object_from_type {
  class Program {
    static void Main(string[] args) {
      int i = 123;
      Type t = i.GetType();
      Object n = Activator.CreateInstance(t);
      n = 15;
      Console.WriteLine(n);
    }
  }
}

輸出:

15

在上面的程式碼中,我們在執行時建立了一個型別為 int32 的例項,而沒有使用 C# 中的 Activator.CreateInstance() 方法指定資料型別。首先,我們使用 C# 中的 i.GetType() 方法確定變數 i 的型別。然後,我們使用 Activator.CreateInstance() 方法建立了該型別的例項。Activator.CreateInstance() 方法會自動為該資料型別找到最佳的建構函式,並使用該例項建立一個例項。然後,我們用值 15 初始化新例項 n 並列印出來。

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