How to reflect the name of the type supplied as a generic?

How to reflect the name of the type that comes as a generic parameter? I would really like to know how this is done both in C # and in VB.NET. See the following sample code and expected answer.

In C #:

public void Test<T>()
{
     Console.WriteLine("The supplied type is {0}",???)
}

In VB.NET

Public Sub Test(Of T)()
     Console.WriteLine("The supplied type is {0}",???)
End Sub

Execution Test<String>()or Test(Of String)()should produce:

The supplied type is String
+3
source share
2 answers

C # ( typeof operator):

public void Test<T>()
{
    Console.WriteLine("The supplied type is {0}", typeof(T));
}

VB.NET ( GetType statement ):

Public Sub Test(Of T)()
    Console.WriteLine("The supplied type is {0}", GetType(T))
End Sub

# typeof(T) VB.NET GetType(T) System.Type, Type. System.Type .ToString() . Name , typeof(T).Name GetType(T).Name # VB.NET .

+16

, , 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

+5
source

Source: https://habr.com/ru/post/1752703/


All Articles