我想编写一个带List<Object>
的函数,并返回一个原始列表,该列表被转换为指定对象类型List<ObjectType>
的列表,知道原始列表中的对象是类型ObjectType
。诀窍是ObjectType
可以是任何类型,我发现使用反射。很抱歉没有代码,但我没理由知道我甚至可能会这样做。
答案 0 :(得分:8)
如果您知道列表中的每个项目都是ObjectType
类型,您可以这样做:
List<object> sourceList = new List<object>() { 1, 2, 3 };
List<int> resultList = sourceList.Cast<int>().ToList();
如果您确实想以通用方式转换列表中的每个项目,最简单的方法是执行以下操作:
public static IEnumerable<T> ConvertTo<T>(this IEnumerable items)
{
return items.Cast<object>().Select(x => (T)Convert.ChangeType(x, typeof(T)));
}
这将作为扩展方法实现,因此您可以编写:
List<object> sourceList = new List<object>() { 1, 2, 3 };
List<string> resultList = sourceList.ConvertTo<string>().ToList();
如果在编译时不知道目标类型,则确实需要使用反射。像这样的东西会起作用:
class ListUtil
{
public static List<T> ConvertToList<T>(this IEnumerable items)
{
// see method above
return items.ConvertTo<T>().ToList();
}
public static IList ConvertToList(this IEnumerable items, Type targetType)
{
var method = typeof(ListUtil).GetMethod(
"ConvertToList",
new[] { typeof(IEnumerable) });
var generic = method.MakeGenericMethod(targetType);
return (IList)generic.Invoke(null, new[] { items });
}
}
现在你可以这样称呼它:
List<object> sourceList = new List<object>() { 1, 2, 3 };
IList resultList = ListUtil.ConvertToList(sourceList, typeof(string));
resultList.GetType(); // List<string>
当然,使用此方法可以避免任何编译时类型的安全性。