1. 简介
扩展方法是 C#3.0
引入的新特性,使用它,允许你向现有的类添加新的方法,而无需修改原始类的代码或创建继承关系
2. 特点
- 定义方法拓展时,需要将其定义为静态类(static class)
- 方法拓展的第一个参数必须是要拓展的类型,使用
this
关键字标记。这个参数表示调用该拓展方法的实例。 - 方法拓展所在的命名空间应该被引入到使用该拓展方法的代码文件中。
3. 示例
namespace ExtensionMethodsExample
{
public static class IntExtensions
{
// 方法拓展:计算整数的平方
public static int Square(this int num)
{
return num * num;
}
// 方法拓展:计算整数的平方,再加上某个值
public static int SquareAdd(this int num, int add)
{
return num * num + add;
}
}
class Program
{
static void Main()
{
int number = 5;
int result = number.Square(); // 使用方法拓展
int result1 = number.SquareAdd(1) // 带参数的方法拓展
Console.WriteLine("Square of {0} is {1}", number, result);
}
}
}