How to call an extension method of a dynamic type?

后端 未结 2 1401
醉话见心
醉话见心 2021-01-07 17:28

I\'m reading the book \'C# in Depth, 2nd Edition\' of Jon Skeet. He said that we can call extension methods with dynamic arguments using two workarounds, just as

<         


        
2条回答
  •  渐次进展
    2021-01-07 18:08

    Like this:

    dynamic numbers = Enumerable.Range(10, 10);
    var firstFive = Enumerable.Take(numbers, 5);
    

    In other words, just call it as a static method instead of as an extension method.

    Or if you know an appropriate type argument you could just cast it, which I'd typically do with an extra variable:

    dynamic numbers = Enumerable.Range(10, 10);
    var sequence = (IEnumerable) numbers;
    var firstFive = sequence.Take(5);
    

    ... but if you're dealing with dynamic types, you may well not know the sequence element type, in which case the first version lets the "execution time compiler" figure it out, basically.

提交回复
热议问题