问题
I'm currently using Generics to make some dynamic methods, like creating an object and filling the properties with values.
Is there any way to "dynamically" create the Generic without knowing the type? For example:
List<String> = new List<String>()
is a predefinied way, but
List<(object.GetType())> = new List<(object.GetType()>()
isn't working... But can it?
This isn't working (Is there a similiar 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 a "Type" and create an object from that without using Generics? I have only used Generics in methods so far, but is it possible to use the same way on variables? I have to define a Generic (T) before the method, so can I do the same on variables before "creating" them?
...or how to use "Activator" to create an object with Properties instead of Parameters. Like you do here:
// With parameters values
Test t = new Test("Argument1", Argument2);
// With properties
Test t = new Test { Argument1 = "Hello", Argument2 = 123 };
回答1:
You can use MakeGenericType
:
Type openListType = typeof(List<>);
Type genericListType = openListType.MakeGenericType(obj.GetType());
object instance = Activator.CreateInstance(genericListType);
回答2:
You can use the MakeGenericType method to get the generic type for a particular 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>
回答3:
When you use the object initializer, it's just using a default constructor (no parameters), then setting the individual properties after the object is constructed.
The code above is close - but var
won't work here, since it's just a compile-time type inferrence. Since you're already using reflection, you can just use System.Object
:
object propertyValue = values[p.Name];
The SetValue
call will work fine with System.Object
.
来源:https://stackoverflow.com/questions/10708925/creating-generic-variables-from-a-type-how-or-use-activator-createinstance