如何调用动态类型的扩展方法?

发布于 2024-10-21 13:37:47 字数 384 浏览 2 评论 0原文

我正在阅读 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

渡你暖光 2024-10-28 13:37:47

就像这样:

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

换句话说,只需将其作为静态方法调用,而不是作为扩展方法。

或者如果你知道一个合适的类型参数,你可以直接转换它,我通常会使用一个额外的变量来做到这一点:

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

...但是如果你正在处理动态类型,你很可能不知道序列元素类型,在这种情况下,第一个版本基本上让“执行时编译器”弄清楚。

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.

断舍离 2024-10-28 13:37:47

扩展方法只是一个语法糖,它会被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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文