[英]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.