如何扩展类?
扩展方法被定义为static
方法,但它们是通过实例方法语法进行调用的。第一个参数指定方法操作的类型。参数前面是this
修饰符。仅当使用using
指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str) // 扩展String类的方法
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
namespace Extension_Methods_Sample
{
//使用 using 指令引入 namespace: ExtensionMethods
using CustomExtensions;
class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
int i = s.WordCount(); // 调用该扩展方法
System.Console.WriteLine("Word count of s is {0}", i);
}
}
}
扩展类并未违反封装原则,因为扩展方法无法访问它们所扩展的类型中的专有变量。