原文来源于MSDN
定义和调用扩展方法
- 定义一个静态类以包含扩展方法。
- 该类必须对客户端代码可见。
- 将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
- 该方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。
- 在调用代码中,添加一条 using 指令以指定包含扩展方法类的命名空间。
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);
}
}