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