Can you instantiate a template class at runtime using C #

Is it possible to instantiate a template class at run time, for example:

Type type = Type.GetType("iTry.Workflow.Person"); WorkflowPropertyViewModel<type> propViewModel = new WorkflowPropertyViewModel<type>(); 

This obviously does not work. Is there any other way to do this?

The Generic class is as follows:

 public class WorkflowPropertyViewModel<T> : IProperty<T> { public Task<T> ValueAsync { get; set; } public T Value { get; set; } public IQueryable<T> PossibleItems { get; set; } } 
+4
source share
3 answers

Yes, you can instantiate a generic class with a type known only at run time, for example:

 public class A { } public class U<T> { public TX { get; set; } } static void Main(string[] args) { Type a = typeof(A); Type u = typeof(U<>); dynamic uOfA = Activator.CreateInstance(u.MakeGenericType(a)); uOfA.X = new A(); Console.WriteLine(uOfA.GetType()); Console.WriteLine(uOfA.X.GetType()); } 

However, this snippet uses reflection and dynamic typing, which can cause many maintenance problems, so you would be better off using them very carefully or finding a simpler solution.

+2
source

You can create an object of any type specified by a Type object:

 object o = Activator.CreateInstance(type); 

This assumes the type has a default constructor. There are other Activator methods for passing constructor parameters:

http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

To get a specific generic type, you can call MakeGenericType to determine your generic type

http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx

So overall it looks something like this:

 var type = Type.GetType("iTry.Workflow.Person"); var genericType = typeof(WorkflowPropertyViewModel<>).MakeGenericType(type); var o = Activator.CreateInstance(genericType); 
+6
source

Try the following:

 object o = Activator.CreateInstance(typeof(WorkflowPropertyViewModel<>).MakeGenericType(new Type[] {type})); 

Please note that in the code you cannot easily refer to this type unless it implements another non-general interface - therefore you need to use an object instead or use a larger reflection.

+2
source

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


All Articles