![](/img/trans.png)
[英]Activator.CreateInstance(string) and Activator.CreateInstance<T>() difference
[英]Activator.CreateInstance with string
我試圖從字段名稱匹配的另一個List <U>填充通用List <T>,類似於下面未經測試的偽代碼。 我遇到問題的地方是例如T是一個字符串,它沒有無參數構造函數。 我嘗試將字符串直接添加到結果對象,但這給了我一個明顯的錯誤-字符串不是TypeT。關於如何解決此問題的任何想法? 感謝您的指導。
public static List<T> GetObjectList<T, U>(List<U> givenObjects)
{
var result = new List<T>();
//Get the two object types so we can compare them.
Type returnType = typeof(T);
PropertyInfo[] classFieldsOfReturnType = returnType.GetProperties(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Public);
Type givenType = typeof(U);
PropertyInfo[] classFieldsOfGivenType = givenType.GetProperties(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Public);
//Go through each object to extract values
foreach (var givenObject in givenObjects)
{
foreach (var field in classFieldsOfReturnType)
{
//Find where names match
var givenTypeField = classFieldsOfGivenType.Where(w => w.Name == field.Name).FirstOrDefault();
if (givenTypeField != null)
{
//Set the value of the given object to the return object
var instance = Activator.CreateInstance<T>();
var value = field.GetValue(givenObject);
PropertyInfo pi = returnType.GetProperty(field.Name);
pi.SetValue(instance, value);
result.Add(instance);
}
}
}
return result;
}
如果T
是string
並且您已經創建了自定義代碼, givenObject
轉換為字符串,則只需對object
進行中間轉換,即可將其添加到List<T>
:
public static List<T> GetObjectList2<T, U>(List<U> givenObjects) where T : class
{
var result = new List<T>();
if (typeof(T) == typeof(string))
{
foreach (var givenObject in givenObjects)
{
var instance = givenObject.ToString(); // Your custom conversion to string.
result.Add((T)(object)instance);
}
}
else
{
// Proceed as before
}
return result;
}
順便說一句,您要添加一個instance
的T
,以result
針對每個屬性 T
,在匹配的屬性名U
並為每個項目givenObjects
。 即,如果givenObjects
是長度為1的列表,而T
是具有10個匹配屬性的類,則result
可能以10個條目結束。 這看起來不對。 另外,您需要注意索引屬性 。
作為此方法的替代方法,請考慮使用Automapper ,或使用Json.NET將List<U>
序列化為JSON,然后反序列化為List<T>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.