扩展方法
扩展方法能够向现有类型添加方法,而无需创建新的派生类型、重新编译或以其他的方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例一样调用。
扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以this
修饰符为前缀。当使用using
指令才能将扩展方法添加到当前范围中。
程序示例
public static class ExtensionMethod
{
public static void ExtensionMethodStr(this string str)
{
Console.WriteLine("ExtensionMethodStr - {0}",str);
}
public static void ExtensionMethodInt(this int a)
{
Console.WriteLine("ExtensionMethodInt - {0}",a);
}
}
class Program
{
static void Main(string[] args)
{
string a = "AAA";
int b = 2;
a.ExtensionMethodStr();
b.ExtensionMethodInt();
Console.ReadKey();
}
}
但扩展方法不能与对象的其他方法同名,否则将不会被调用。
程序示例
public static class ExtensionMethod
{
public static void MethodA(this A a)
{
Console.WriteLine("---Extension - MethodA --");
}
}
public class A
{
public void MethodA()
{
Console.WriteLine("---A - MethodA --");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.MethodA(); //这里会调用A类里面的方法,不会调用扩展方法
Console.ReadKey();
}
}
给枚举扩展方法
public enum Color
{
Black,
White,
Blue,
}
public static class ExtensionMethod
{
public static void ExtensionEnum(this Color color)
{
Console.WriteLine("I'm {0}", color);
}
}
class Program
{
static void Main(string[] args)
{
Color.Blue.ExtensionEnum();
Console.ReadKey();
}
}