【问题标题】:cast reflected result from object to list<TDest> where TDest is enum将反射结果从对象投射到列表<TDest>,其中 TDest 是枚举
【发布时间】:2019-08-26 14:04:01
【问题描述】:

如何投射反射结果 从对象到List&lt;TDynamicType&gt;

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&lt;tDest&gt; list = sourceList.Cast&lt;tDest&gt;().ToList() ?
  • @JeroenvanLangen 是的,但我没有列表,我有一个对象...(列表类型在运行时解析)
  • 您不能强制转换为编译时未知的类型。你想用list 做什么,为什么需要演员表?
  • @giacomo 如果对象的实际运行时类型 根本不是列表类型,则强制转换对您没有帮助。或者你是说你确实有一个列表,但是对它的引用被声明为object?如果是这种情况,您可能必须转换为非泛型 System.Collecitons.IList,然后将这些项目分别转换为有用的东西——也许是所有潜在的TDynamicTypes 都知道实现的接口。
  • 如果您不需要添加项目,并且如果tDest 的任何值可以假设实现了某个接口IWhatever,该接口在编译时已知的,你可以投到IEnumerable&lt;IWhatever&gt;

标签: c# .net reflection


【解决方案1】:

可以尝试投射到IList&lt;TDynamicType&gt;,如下所示:var list = sourceList.Cast&lt;IList&lt;TDynamicType&gt;&gt;().ToList()

【讨论】:

  • 我没有sourceList,它只是一个对象
  • 好的..我看到了你发布的解决方案,我想你也可以试试Activator.CreateInstance()
【解决方案2】:

我已经这样解决了,将对象强制转换为iEnumerableOfInteger(强制转换为listOfObject给null),然后解析。

                Type tSource = item.SourceType;     //enum
                Type tDest = item.DestinationType;  //enum

                MethodInfo method = typeof(EnumConverters).GetMethod("GetEnumValues");
                MethodInfo methodGenericSource = method.MakeGenericMethod(tSource);
                object objEnumsSource = methodGenericSource.Invoke(null, null);

                //var listObj = (IEnumerable<object>)objEnumsSource;//throw
                var listInt = (IEnumerable<int>)objEnumsSource;
                foreach (var i in listInt)
                {
                    if (!Enum.IsDefined(tSource, i))
                        throw new ApplicationException($"!Enum.IsDefined({tSource.FullName}, {i})");

                    var o = Enum.ToObject(tSource, i);
                    var e = Convert.ChangeType(o, tSource);
                }

【讨论】:

  • 你最终不需要 both Enum.ToObjectConvert.ChangeType
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-02
  • 2011-10-05
  • 2016-07-13
  • 1970-01-01
相关资源
最近更新 更多