繁体   English   中英

使用反射方法调用类型转换时出错

[英]Error in type conversion using reflection method invoke

我有一个方法调用如下:

splitByRegex(regexPattern, lines, ref lineIndex, capacity, result =>
{
      List<object> res = result.Select(selector).ToList();
      MessageBox.Show(res[0].GetType().ToString());
      collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });
});

splitByRegex方法将拆分数据并返回result

我必须将获得的result添加到通用collection中。

selector类型 function: Func<Tuple<string, string, string>, object>

示例选择器 Function: x => new Merchant { MerchantName = x.Item1, Count = Convert.ToInt64(x.Item2), Percentage = Convert.ToDecimal(x.Item3) }

使用反射执行AddRange方法调用时: collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });

我收到以下错误:

Object of type 'System.Linq.Enumerable+WhereSelectListIterator 2[System.Tuple 3[System.String,System.String,System.String],System.Object]' cannot be converted to type 'System.Collections.Generic.IEnumerable` 1 [处理.商家]'。

当我尝试从List<object> res MessageBox.Show(res[0].GetType().ToString()); ,它显示为Merchant类型 object。 那么为什么我会收到这个错误?

@John - 感谢您将我指向Eric 的帖子 这很清楚。 我通过不调用AddRange方法来修复它,而是为获得的结果中的每个元素调用通用集合的Add方法。

splitByRegex(regexPattern, lines, ref lineIndex, capacity, result =>
{
     MethodInfo method = collection.GetType().GetMethod("Add");
     result.Select(selector).ToList().ForEach(item => method.Invoke(collection, new object[] { item }));
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM