如何调用动态类型的扩展方法是什么? [英] How to call an extension method of a dynamic type?

查看:108
本文介绍了如何调用动态类型的扩展方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读乔恩斯基特的书C#中的深度,第二版。他说,我们可以调用使用两种解决方法,就像

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.

非常感谢。

推荐答案

这样的:

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.

这篇关于如何调用动态类型的扩展方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆