C#扩展方法

扩展方法

  扩展方法能够向现有类型添加方法,而无需创建新的派生类型、重新编译或以其他的方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例一样调用。
  扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值