, , T , .GetType():
public void Test<T>(T target)
{
Console.WriteLine("The supplied type is {0}", target.GetType());
}
(typeof , .GetType() ).
, : typeof(T) type, .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. X
: ConsoleApplication2. X
T IsAssignable From Target Type: True
TypeY :
TypeOf T: ConsoleApplication2. X
: ConsoleApplication2. TypeY
T IsAssignable From Target Type: True
source
share