簡體   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