How to I reflect back the name of a type that is supplied as a generic parameter? I would really like to know how this is done in both C# and VB.NET. See the following example code and expected response.
In C#:
public void Test<T>()
{
Console.WriteLine("The supplied type is {0}",???)
}
In VB.NET
Public Sub Test(Of T)()
Consol开发者_StackOverflow中文版e.WriteLine("The supplied type is {0}",???)
End Sub
Executing Test<String>()
or Test(Of String)()
should produce:
The supplied type is String
C# (typeof operator):
public void Test<T>()
{
Console.WriteLine("The supplied type is {0}", typeof(T));
}
VB.NET (GetType operator):
Public Sub Test(Of T)()
Console.WriteLine("The supplied type is {0}", GetType(T))
End Sub
C#'s typeof(T)
and VB.NET's GetType(T)
return a System.Type
object that has properties and methods for retrieving information about a specific Type
. By default, System.Type
's .ToString()
method will return the fully qualified name of the Type. To return only the Name
of the type, call typeof(T).Name
or GetType(T).Name
in C# or VB.NET, respectively.
Darin's answer is correct, but it's also worth noting that if you receive an instance of T
as a parameter you can use .GetType()
as well:
public void Test<T>(T target)
{
Console.WriteLine("The supplied type is {0}", target.GetType());
}
Just a different approach (typeof
will inspect the type argument whereas .GetType()
works with an instance of the type).
As Daniel notes in the comments there is a nuance to consider: typeof(T)
will return the type-argument's Type, whereas .GetType()
will return the exact type of the object--which may inherit from T
, and typeof(T).IsAssignableFrom(target.GetType())
may return true--but the specific concrete types may differ.
An example:
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()));
}
}
}
Resulting output:
Passing in an instance of TypeX as the parameter:
TypeOf T: ConsoleApplication2.TypeX
Target Type: ConsoleApplication2.TypeX
T IsAssignable From Target Type: True
Passing in an instance of TypeY as the parameter:
TypeOf T: ConsoleApplication2.TypeX
Target Type: ConsoleApplication2.TypeY
T IsAssignable From Target Type: True
精彩评论