How to call an extension method of a dynamic type?

Deadly 提交于 2019-12-30 07:51:45

问题


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

dynamic size = 5;
var numbers = Enumerable.Range(10, 10);
var error = numbers.Take(size);
var workaround1 = numbers.Take((int) size);
var workaround2 = Enumerable.Take(numbers, size);

Then he said "Both approaches will work if you want to call the extension method with the dynamic value as the implicit this value". I don't know how to achieve it.

Thanks a lot.


回答1:


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<int>) 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.




回答2:


Extension method just a syntactic sugar, it will be converted as a normal method calling by c# compiler. This conversion is dependent with current syntax context (Which namespaces are imported by using statement).

Dynamic variable is process by runtime. this time, CLR cannot get enough syntax context information to deciding which extension method used. So, it is not work.



来源:https://stackoverflow.com/questions/5270782/how-to-call-an-extension-method-of-a-dynamic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!