Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use typeof or GetType() as Generic's Template?

Tags:

.net

generics

If it's harder to explain using words, let's look at an example I have a generic function like this

void FunctionA<T>() where T : Form, new() { } 

If I have a reflected type, how do I use it with the above function? I'm looking forward to do this

Type a = Type.GetType("System.Windows.Forms.Form"); FunctionA<a>(); 

Of cause the above method doesn't work.

like image 439
faulty Avatar asked Nov 19 '08 16:11

faulty


People also ask

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

How do I use GetType?

The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.

What is GetType () name in C#?

GetType or Assembly. GetTypes method to get Type objects. If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic. If typeName cannot be found, the call to the GetType(String) method returns null .

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.


1 Answers

class Program {     static void Main(string[] args)     {         int s = 38;           var t = typeof(Foo);         var m = t.GetMethod("Bar");         var g = m.MakeGenericMethod(s.GetType());         var foo = new Foo();         g.Invoke(foo, null);         Console.ReadLine();     } }  public class Foo {     public void Bar<T>()     {         Console.WriteLine(typeof(T).ToString());     } } 

it works dynamicaly and s can be of any type

like image 119
gdbdable Avatar answered Sep 19 '22 15:09

gdbdable