如何调用动态类型的扩展方法?
我正在阅读 Jon Skeet 的《C# in Depth, 2nd Edition》一书。他说我们可以使用两种解决方法来调用带有动态参数的扩展方法,就像
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);
然后他说的“如果您想使用动态值作为隐式 this
值来调用扩展方法,两种方法都可以工作” 。我不知道如何实现它。
多谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就像这样:
换句话说,只需将其作为静态方法调用,而不是作为扩展方法。
或者如果你知道一个合适的类型参数,你可以直接转换它,我通常会使用一个额外的变量来做到这一点:
...但是如果你正在处理动态类型,你很可能不知道序列元素类型,在这种情况下,第一个版本基本上让“执行时编译器”弄清楚。
Like this:
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:
... 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.
扩展方法只是一个语法糖,它会被c#编译器转换为普通方法调用。此转换取决于当前语法上下文(哪些命名空间是通过 using 语句导入的)。
动态变量由运行时处理。这次,CLR 无法获得足够的语法上下文信息来决定使用哪种扩展方法。所以,这不是工作。
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.