Deu*_*ion 6 c# generics reflection types dynamically-generated
我目前正在使用Generics来制作一些动态方法,比如创建一个对象并用值填充属性.
有没有办法在不知道类型的情况下"动态"创建Generic?例如:
List<String> = new List<String>()
Run Code Online (Sandbox Code Playgroud)
是一种预先确定的方式,但是
List<(object.GetType())> = new List<(object.GetType()>()
Run Code Online (Sandbox Code Playgroud)
不行......但是可以吗?
这不起作用(有类似的方法吗?)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
那么,简而言之:如何在不使用泛型的情况下采用"类型"并从中创建对象?到目前为止,我只在方法中使用了泛型,但是可以在变量上使用相同的方法吗?我必须在方法之前定义Generic(T),所以我可以在"创建"它们之前对变量做同样的事情吗?
...或者如何使用"Activator"创建一个带有Properties而不是Parameters的对象.就像你在这里一样:
//使用参数值
Test t = new Test("Argument1", Argument2);
Run Code Online (Sandbox Code Playgroud)
//使用属性
Test t = new Test { Argument1 = "Hello", Argument2 = 123 };
Run Code Online (Sandbox Code Playgroud)
Adi*_*ter 13
你可以使用MakeGenericType:
Type openListType = typeof(List<>);
Type genericListType = openListType.MakeGenericType(obj.GetType());
object instance = Activator.CreateInstance(genericListType);
Run Code Online (Sandbox Code Playgroud)
您可以使用MakeGenericType方法获取特定类型参数的泛型类型:
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>
Run Code Online (Sandbox Code Playgroud)