明确使用扩展方法 [英] Explicitly use extension method

查看:63
本文介绍了明确使用扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List<T>,想以相反的顺序取回值.我不想要反转列表本身.

I'm having a List<T> and want get the values back in reverse order. What I don't want is to reverse the list itself.

这似乎毫无问题,因为IEnumerable<T>有一个Reverse()扩展方法,可以完全满足我的要求.

This seems like no problem at all since there's a Reverse() extension method for IEnumerable<T> which does exactly what I want.

我的问题是,还有List<T>Reverse()方法,该方法可以反转列表本身并返回void.

My problem is, that there's also a Reverse() method for List<T> which reverses the list itself and returns void.

我知道有很多种方法可以以相反的顺序遍历列表,但是我的问题是:

I know there are plenty of ways to traverse the list in reverse order but my question is:

如何告诉编译器我想使用相同名称的扩展方法?

var list = new List<int>(new [] {1, 2, 3});
DumpList(list.Reverse());                   // error

推荐答案

显式绑定到特定扩展方法的最佳方法是使用共享方法语法进行调用.就您而言,您可以这样做:

The best way to explictly bind to a particular extension method is to call it using shared method syntax. In your case, you would do that like:

DumpList(Enumerable.Reverse(list));

这里提到的其他一些方法的问题在于它们不会总是做您想要的事情.例如,像这样投射列表:

The problem with some of the other approaches mentioned here is that they won't always do what you want. For example, casting the list like so:

((IEnumerable)list).Reverse()

最终可能会调用完全不同的方法,具体取决于您导入的名称空间或定义的调用代码类型.

could end up calling a completely different method depending on the namespaces you have imported, or what type the calling code is defined in.

100%确定绑定到特定扩展方法的唯一方法是使用共享方法语法.

The only way to be 100% sure you bind to a particular extension method is to use the shared method syntax.

这篇关于明确使用扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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