![](/img/trans.png)
[英]Unable to use generic method type <T> directly in Activator.CreateInstance
[英]Creating generic variables from a type - How? Or use Activator.CreateInstance() with properties { } instead of parameters ( )?
我目前正在使用Generics來制作一些動態方法,比如創建一個對象並用值填充屬性。
有沒有辦法在不知道類型的情況下“動態”創建Generic? 例如:
List<String> = new List<String>()
是一種預先確定的方式,但是
List<(object.GetType())> = new List<(object.GetType()>()
不行......但是可以嗎?
這不起作用(有類似的方法嗎?)
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);
}
}
那么,簡而言之:如何在不使用泛型的情況下采用“類型”並從中創建對象? 到目前為止,我只在方法中使用了泛型,但是可以在變量上使用相同的方法嗎? 我必須在方法之前定義Generic(T),所以我可以在“創建”它們之前對變量做同樣的事情嗎?
...或者如何使用“Activator”創建一個帶有Properties而不是Parameters的對象。 就像你在這里一樣:
//使用參數值
Test t = new Test("Argument1", Argument2);
//使用屬性
Test t = new Test { Argument1 = "Hello", Argument2 = 123 };
您可以使用MakeGenericType
:
Type openListType = typeof(List<>);
Type genericListType = openListType.MakeGenericType(obj.GetType());
object instance = Activator.CreateInstance(genericListType);
您可以使用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>
當您使用對象初始值設定項時,它只使用默認構造函數(無參數),然后在構造對象后設置各個屬性。
上面的代碼很接近 - 但var
在這里不起作用,因為它只是一個編譯時類型的推論。 由於您已經在使用反射,因此您只需使用System.Object
:
object propertyValue = values[p.Name];
SetValue
調用將與System.Object
一起正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.