Creating shared variables from a type - How? Or use Activator.CreateInstance () with {} properties instead of () parameters?

I am currently using Generics to create dynamic methods, such as creating an object and filling properties with values.

Is there a way to "dynamically" create a Generic without knowing the type? For instance:

List<String> = new List<String>() 

is a predefined way but

 List<(object.GetType())> = new List<(object.GetType()>() 

doesn't work ... But can it?

This does not work (Is there a similar approach that works?)

  public T CreateObject<T>(Hashtable values) { // If it has parameterless constructor (I check this beforehand) T obj = (T)Activator.CreateInstance(typeof(T)); foreach (System.Reflection.PropertyInfo p in typeof(T).GetProperties()) { // Specifically this doesn't work var propertyValue = (p.PropertyType)values[p.Name]; // Should work if T2 is generic // var propertyValue = (T2)values[p.Name]; obj.GetType().GetProperty(p.Name).SetValue(obj, propertyValue, null); } } 

So, in short: how to take the “Type” and create an object from it without using Generics? I used only Generics methods in the methods, but can the same variables be used? I have to define Generic (T) before the method, so can I do the same on the variables before they are "created"?

... or how to use the Activator to create an object using properties instead of parameters. How are you here:

// With parameter values

 Test t = new Test("Argument1", Argument2); 

// With properties

 Test t = new Test { Argument1 = "Hello", Argument2 = 123 }; 
+6
source share
3 answers

You can use MakeGenericType :

 Type openListType = typeof(List<>); Type genericListType = openListType.MakeGenericType(obj.GetType()); object instance = Activator.CreateInstance(genericListType); 
+13
source

You can use the MakeGenericType method to get a generic type for a specific type argument:

 var myObjListType = typeof(List<>).MakeGenericType(myObject.GetType()); var myObj = Activator.CreateInstance(myObjListType); // MyObj will be an Object variable whose instance is a List<type of myObject> 
+5
source

When you use an object initializer, it simply uses the default constructor (without parameters), and then sets the individual properties after creating the object.

The above code is close, but var will not work here, as it simply indicates the type of compilation time. Since you are already using reflection, you can simply use System.Object :

 object propertyValue = values[p.Name]; 

The SetValue call SetValue fine with System.Object .

+1
source

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


All Articles