What do you call a generic method if you only know the type parameter at runtime?

I have this method:

public List<T> SomeMethod<T>( params ) where T : new() 

So, I want to call it SomeMethod , which is great if I know the type:

 SomeMethod<Class1>(); 

But if I only have Class1 at runtime, can't I name it?

So how to call SomeMethod with an unknown type T? I got Type using reflection.

I have a type type, but SomeMethod<Type | GetType()> SomeMethod<Type | GetType()> does not work.

Update 7. May:

Here is an example of the code I want to achieve:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication63 { public class DummyClass { } public class Class1 { public string Name; } class AssemblyTypesReflection { static void Main(string[] args) { object obj = new Class1() { Name = "John" } ; Assembly assembly = Assembly.GetExecutingAssembly(); var AsmClass1 = (from i in assembly.GetTypes() where i.Name == "Class1" select i).FirstOrDefault(); var list = SomeMethod<AsmClass1>((AsmClass1)obj); //Here it fails } static List<T> SomeMethod<T>(T obj) where T : new() { return new List<T> { obj }; } } } 

This is a demonstration from a wider context.

+6
source share
2 answers

You need to call it with reflection:

 var method = typeof(SomeClass).GetMethod("SomeMethod"); method.MakeGenericMethod(someType).Invoke(...); 
+8
source

You can use the dynamic keyword in C # 4. You also need .NET 4.0 or higher .:

 SomeMethod((dynamic)obj); 

Runtime displays the actual type argument and makes the call. It fails if obj is null, since then type information is missing. null in C # has no type.

+2
source

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


All Articles