C# 实现和调用自定义扩展方法
2016-07-22 14:49
639 查看
定义和调用扩展方法
定义一个静态类以包含扩展方法。该类必须对客户端代码可见。
将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
该方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。
在调用代码中,添加一条 using 指令以指定包含扩展方法类的命名空间。
按照与调用类型上的实例方法一样的方式调用扩展方法。
请注意,第一个参数不是由调用代码指定的,因为它表示正应用运算符的类型,并且编译器已经知道对象的类型。 您只需通过 n 为这两个形参提供实参。
示例
下面的示例在 CustomExtensions.StringExtension 类中实现了一个名为 WordCount 的扩展方法。
该方法对 String 类进行操作,而该类被指定为第一个方法参数。
CustomExtensions 命名空间被导入到应用程序命名空间中,并且该方法是在 Main 方法内调用的
定义一个静态类以包含扩展方法。该类必须对客户端代码可见。
将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
该方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。
在调用代码中,添加一条 using 指令以指定包含扩展方法类的命名空间。
按照与调用类型上的实例方法一样的方式调用扩展方法。
请注意,第一个参数不是由调用代码指定的,因为它表示正应用运算符的类型,并且编译器已经知道对象的类型。 您只需通过 n 为这两个形参提供实参。
示例
下面的示例在 CustomExtensions.StringExtension 类中实现了一个名为 WordCount 的扩展方法。
该方法对 String 类进行操作,而该类被指定为第一个方法参数。
CustomExtensions 命名空间被导入到应用程序命名空间中,并且该方法是在 Main 方法内调用的
using System.Linq; using System.Text; using System; namespace CustomExtensions { //Extension methods must be defined in a static class public static class StringExtension { // This is the extension method. // The first parameter takes the "this" modifier // and specifies the type for which the method is defined. public static int WordCount(this String str) { return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length; } } } namespace Extension_Methods_Simple { //Import the extension method namespace. using CustomExtensions; class Program { static void Main(string[] args) { string s = "The quick brown fox jumped over the lazy dog."; // Call the method as if it were an // instance method on the type. Note that the first // parameter is not specified by the calling code. int i = s.WordCount(); System.Console.WriteLine("Word count of s is {0}", i); } } }
相关文章推荐
- C# 扩展方法
- C#实现输入一个字符串输出该字符串字符的所有排列方式
- C#程序猿电脑重装记录
- C#获取本机的外网IP
- C# 读COM PORT
- C#获取程序集自动增加的版本号和编译时间
- C# 通过Thrift 1 操作 HBase
- C#------编码规范
- Webservice的简单应用(wsdl的获取)
- C# xml文档读写
- C#泛型类与接口
- C# 值类型与引用类型详解
- 匿名方法 Lambda表达式
- C# new virtual和override 区别
- 多播委托
- .NET之美——C# 中的委托和事件
- C# 调用WebService的3种方式 :直接调用、根据wsdl生成webservice的.cs文件及生成dll调用、动态调用
- .NET之美——C#中的委托和事件(续)
- .NET之美——1.1 C#中的泛型
- c#的DateTime.Now函数详解