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