mercredi 15 août 2018

Cannot cast List

I am having trouble casting a List<int> or int[] to IEnumerable<object> for further processing.

Here is the code snippet:

var dividedSubtasks = (IEnumerable<object>)someMethod.Invoke(instance, new[] {parsedTask});

This calls a method using reflection. That method returns IEnumerable<int>. (the exact type is List<int>, but I have also tried int[]). It throws an exception when casting.

I tried casting with as IEnumerable<object>, it did not work either.

I have tested in the debugger that the returned value is, in fact, correct. In Visual Studio's Immediate Window I tried casting the value to IEnumerable<object> - it worked without any problems. I cannot get it to work in code, though.

Here is the invoked method:

    public IEnumerable<int> DivideTask(string task)
    {
        return task.Split(',')
            .Select(int.Parse).ToList();
    }

How can I cast the returned value without producing exceptions?





Aucun commentaire:

Enregistrer un commentaire