Darin的答案是正確的,但它也是值得注意的是,如果您收到的T
實例作爲參數,你可以使用.GetType()
還有:
public void Test<T>(T target)
{
Console.WriteLine("The supplied type is {0}", target.GetType());
}
只是一種不同的方法(typeof
將檢查類型參數而.GetType()
與一起使用類型的實例)。
由於丹尼爾在評論中指出存在細微差別來考慮:typeof(T)
將返回類型參數的類型,而.GetType()
將返回對象的確切類型 - 這可能從T
繼承和typeof(T).IsAssignableFrom(target.GetType())
可能會返回true - 但具體的具體類型可能會有所不同。
一個例子:
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
GenericClass<TypeX>.GenericMethod(new TypeX());
GenericClass<TypeX>.GenericMethod(new TypeY());
Console.ReadKey();
}
}
public class TypeX {}
public class TypeY : TypeX {}
public static class GenericClass<T>
{
public static void GenericMethod(T target)
{
Console.WriteLine("TypeOf T: " + typeof(T).FullName);
Console.WriteLine("Target Type: " + target.GetType().FullName);
Console.WriteLine("T IsAssignable From Target Type: " + typeof(T).IsAssignableFrom(target.GetType()));
}
}
}
結果輸出:
在而TYPEx實例傳遞作爲參數:
TypeOf運算T:ConsoleApplication2。 TypeX
目標類型:ConsoleApplication2。而TYPEx
ŤIsAssignable從目標類型:真
傳遞鍵入y作爲參數的實例:
TypeOf運算T:ConsoleApplication2。 TypeX
目標類型:ConsoleApplication2。 鍵入y
牛逼IsAssignable從目標類型:真
來源
2010-07-01 19:42:37
STW
+1了確切的答案的OP是:-P – STW 2010-07-01 20:14:25
感謝您的回答後!這幫助我開始了。我在'System.Type'附加了一些附加信息,以便其他人知道它實際上是一個具有屬性和方法的第一類對象。如果我添加了任何不正確的東西,請隨意編輯它。 – 2010-07-01 20:38:34