您好,欢迎访问一九零五行业门户网

C# 参数带this是什么意思(扩展方法)

扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。 对于用 c# 和 visual basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法之间没有明显的差异。
最常见的扩展方法是 linq 标准查询运算符,它将查询功能添加到现有的 system.collections.ienumerable 和 system.collections.generic.ienumerable<t> 类型。 若要使用标准查询运算符,请先使用 using system.linq 指令将它们置于范围中。 然后,任何实现了 ienumerable<t> 的类型看起来都具有 groupby、orderby、average 等实例方法。 在 ienumerable<t>类型的实例(如 list<t> 或 array)后键入“dot”时,可以在 intellisense 语句完成中看到这些附加方法。
下面的示例演示如何对一个整数数组调用标准查询运算符 orderby 方法。 括号里面的表达式是一个 lambda 表达式。 很多标准查询运算符采用 lambda 表达式作为参数,但这不是扩展方法的必要条件。 有关详细信息,请参阅 lambda 表达式(c# 编程指南)。
c#
class extensionmethods2     {    static void main()     {                     int[] ints = { 10, 45, 15, 39, 21, 26 };        var result = ints.orderby(g => g);        foreach (var i in result)         {             system.console.write(i +  );         }                }         }//output: 10 15 21 26 39 45
扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 仅当你使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。
下面的示例演示为 system.string 类定义的一个扩展方法。 请注意,它是在非嵌套的、非泛型静态类内部定义的:
c#
namespace extensionmethods {    public static class myextensions     {        public static int wordcount(this string str)         {            return str.split(new char[] { ' ', '.', '?' },                               stringsplitoptions.removeemptyentries).length;         }     }    }
可使用此 using 指令将 wordcount 扩展方法置于范围中:
using extensionmethods;
而且,可以使用以下语法从应用程序中调用该扩展方法:
string s = hello extension methods; int i = s.wordcount();
在代码中,可以使用实例方法语法调用该扩展方法。 但是,编译器生成的中间语言 (il) 会将代码转换为对静态方法的调用。 因此,并未真正违反封装原则。 实际上,扩展方法无法访问它们所扩展的类型中的私有变量。
有关详细信息,请参阅如何:实现和调用自定义扩展方法(c# 编程指南)。
通常,你更多时候是调用扩展方法而不是实现你自己的扩展方法。 由于扩展方法是使用实例方法语法调用的,因此不需要任何特殊知识即可从客户端代码中使用它们。 若要为特定类型启用扩展方法,只需为在其中定义这些方法的命名空间添加 using 指令。 例如,若要使用标准查询运算符,请将此 using 指令添加到代码中:
using system.linq;
(你可能还必须添加对 system.core.dll 的引用。)你将注意到,标准查询运算符现在作为可供大多数 ienumerable<t> 类型使用的附加方法显示在 intellisense 中。
说明
尽管标准查询运算符没有显示在 string 的 intellisense 中,但它们仍然可用。
在编译时绑定扩展方法
可以使用扩展方法来扩展类或接口,但不能重写扩展方法。 与接口或类方法具有相同名称和签名的扩展方法永远不会被调用。 编译时,扩展方法的优先级总是比类型本身中定义的实例方法低。 换句话说,如果某个类型具有一个名为 process(int i) 的方法,而你有一个具有相同签名的扩展方法,则编译器总是绑定到该实例方法。 当编译器遇到方法调用时,它首先在该类型的实例方法中寻找匹配的方法。 如果未找到任何匹配方法,编译器将搜索为该类型定义的任何扩展方法,并且绑定到它找到的第一个扩展方法。 下面的示例演示编译器如何确定要绑定到哪个扩展方法或实例方法。
示例
下面的示例演示 c# 编译器在确定是将方法调用绑定到类型上的实例方法还是绑定到扩展方法时所遵循的规则。 静态类 extensions 包含为任何实现了 imyinterface 的类型定义的扩展方法。 类 a、b 和 c 都实现了该接口。
methodb 扩展方法永远不会被调用,因为它的名称和签名与这些类已经实现的方法完全匹配。
如果编译器找不到具有匹配签名的实例方法,它会绑定到匹配的扩展方法(如果存在这样的方法)。
c#
// define an interface named imyinterface.namespace defineimyinterface {    using system;    public interface imyinterface     {        // any class that implements imyinterface must define a method         // that matches the following signature.         void methodb();     } }// define extension methods for imyinterface.namespace extensions {    using system;    using defineimyinterface;    // the following extension methods can be accessed by instances of any      // class that implements imyinterface.     public static class extension     {        public static void methoda(this imyinterface myinterface, int i)         {             console.writeline                 (extension.methoda(this imyinterface myinterface, int i));         }        public static void methoda(this imyinterface myinterface, string s)         {             console.writeline                 (extension.methoda(this imyinterface myinterface, string s));         }        // this method is never called in extensionmethodsdemo1, because each          // of the three classes a, b, and c implements a method named methodb         // that has a matching signature.         public static void methodb(this imyinterface myinterface)         {             console.writeline                 (extension.methodb(this imyinterface myinterface));         }     } }// define three classes that implement imyinterface, and then use them to test// the extension methods.namespace extensionmethodsdemo1 {    using system;    using extensions;    using defineimyinterface;    class a : imyinterface     {        public void methodb() { console.writeline(a.methodb()); }     }    class b : imyinterface     {        public void methodb() { console.writeline(b.methodb()); }             public void methoda(int i) { console.writeline(b.methoda(int i)); }     }    class c : imyinterface     {        public void methodb() { console.writeline(c.methodb()); }             public void methoda(object obj)         {             console.writeline(c.methoda(object obj));         }     }    class extmethoddemo     {        static void main(string[] args)         {            // declare an instance of class a, class b, and class c.             a a = new a();             b b = new b();             c c = new c();            // for a, b, and c, call the following methods:             //      -- methoda with an int argument             //      -- methoda with a string argument             //      -- methodb with no argument.             // a contains no methoda, so each call to methoda resolves to              // the extension method that has a matching signature.             a.methoda(1);           // extension.methoda(object, int)             a.methoda(hello);     // extension.methoda(object, string)             // a has a method that matches the signature of the following call             // to methodb.             a.methodb();            // a.methodb()             // b has methods that match the signatures of the following             // method calls.             b.methoda(1);           // b.methoda(int)             b.methodb();            // b.methodb()             // b has no matching method for the following call, but              // class extension does.             b.methoda(hello);     // extension.methoda(object, string)             // c contains an instance method that matches each of the following             // method calls.             c.methoda(1);           // c.methoda(object)             c.methoda(hello);     // c.methoda(object)             c.methodb();            // c.methodb()         }     } }/* output:     extension.methoda(this imyinterface myinterface, int i)     extension.methoda(this imyinterface myinterface, string s)     a.methodb()     b.methoda(int i)     b.methodb()     extension.methoda(this imyinterface myinterface, string s)     c.methoda(object obj)     c.methoda(object obj)     c.methodb()  */
通用准则
通常,建议你只在不得已的情况下才实现扩展方法,并谨慎地实现。 只要有可能,必须扩展现有类型的客户端代码都应该通过创建从现有类型派生的新类型来达到这一目的。 有关详细信息,请参阅继承(c# 编程指南)。
在使用扩展方法来扩展你无法更改其源代码的类型时,你需要承受该类型实现中的更改会导致扩展方法失效的风险。
如果你确实为给定类型实现了扩展方法,请记住以下几点:
如果扩展方法与该类型中定义的方法具有相同的签名,则扩展方法永远不会被调用。
在命名空间级别将扩展方法置于范围中。 例如,如果你在一个名为 extensions 的命名空间中具有多个包含扩展方法的静态类,则这些扩展方法将全部由 using extensions; 指令置于范围中。
针对已实现的类库,不应为了避免程序集的版本号递增而使用扩展方法。 如果要向你拥有源代码的库中添加重要功能,应遵循适用于程序集版本控制的标准 .net framework 准则。 有关详细信息,请参阅程序集版本控制。
以上就是c# 参数带this是什么意思(扩展方法)的内容。
其它类似信息

推荐信息