jeudi 24 octobre 2019

C# error in type conversion using reflection method invoke

I have a method call as follows:

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 method will split the data and will give back result.

I have to add the obtained result to the generic collection.

Type of selector function: Func<Tuple<string, string, string>, object>

Sample selector Function: x => new Merchant { MerchantName = x.Item1, Count = Convert.ToInt64(x.Item2), Percentage = Convert.ToDecimal(x.Item3) }

While executing AddRange method call using reflection: collection.GetType().GetMethod("AddRange").Invoke(collection, new object[] { res });

I am getting following error:

Object of type 'System.Linq.Enumerable+WhereSelectListIterator2[System.Tuple3[System.String,System.String,System.String],System.Object]' cannot be converted to type 'System.Collections.Generic.IEnumerable`1[Processing.Merchant]'.

When I try to print the type of any one object from the List<object> res MessageBox.Show(res[0].GetType().ToString());, it shows it as Merchant type object. So why am I getting this error?





Aucun commentaire:

Enregistrer un commentaire