C#中typeof關(guān)鍵字如何用于泛型編程

c#
小樊
92
2024-08-12 05:20:33

在C#中,typeof關(guān)鍵字通常用于獲取指定類型的Type對(duì)象。在泛型編程中,可以使用typeof關(guān)鍵字來(lái)獲取泛型類型的Type對(duì)象。例如:

public class GenericClass<T>
{
    public void PrintType()
    {
        Type type = typeof(T);
        Console.WriteLine("Type of T is: " + type);
    }
}

class Program
{
    static void Main()
    {
        GenericClass<int> genericClass = new GenericClass<int>();
        genericClass.PrintType(); // 輸出:Type of T is: System.Int32
    }
}

在上面的示例中,我們定義了一個(gè)泛型類GenericClass,然后在PrintType()方法中使用typeof關(guān)鍵字獲取T類型的Type對(duì)象,并輸出到控制臺(tái)。在Main()方法中,我們實(shí)例化了GenericClass類,并調(diào)用PrintType()方法打印T的類型。

0