【发布时间】:2019-08-26 14:04:01
【问题描述】:
如何投射反射结果
从对象到List<TDynamicType>?
Type tSource = item.SourceType; //enum
Type tDest = item.DestinationType; //enum
MethodInfo method = typeof(EnumConverters).GetMethod("GetEnumValues");
MethodInfo methodGenericSource = method.MakeGenericMethod(tSource);
object enumsSource = methodGenericSource.Invoke(null, null);
// i need to convert enumsSource to List<tDest> (where tDest is enum)
List<tDest> list = ???
是否有像“getResultGeneric”或“getResultOfType”这样的反射函数?
【问题讨论】:
-
你的意思是这样的。
List<tDest> list = sourceList.Cast<tDest>().ToList()? -
@JeroenvanLangen 是的,但我没有列表,我有一个对象...(列表类型在运行时解析)
-
您不能强制转换为编译时未知的类型。你想用
list做什么,为什么需要演员表? -
@giacomo 如果对象的实际运行时类型 根本不是列表类型,则强制转换对您没有帮助。或者你是说你确实有一个列表,但是对它的引用被声明为
object?如果是这种情况,您可能必须转换为非泛型System.Collecitons.IList,然后将这些项目分别转换为有用的东西——也许是所有潜在的TDynamicTypes 都知道实现的接口。 -
如果您不需要添加项目,并且如果
tDest的任何值可以假设实现了某个接口IWhatever,该接口在编译时是已知的,你可以投到IEnumerable<IWhatever>。
标签: c# .net reflection