【Unity】【C#】扩展方法(Extension Method)

1.什么是扩展方法(Extension Method)

扩展方法使编程者能够在不修改原来类的基础上给该类添加方法。

2.为什么使用扩展方法

如调用库中的类时,对库中的类不熟悉,则可以使用扩展方法直接向库中的类添加方法而无需修改库。或是其他不便修改原有类的场景。

3.实现方法

using System;



//扩展方法必须为static
public static class ExpensionMethod
{

    //扩展方法中的方法必须为public static
    //第一个参数格式必须为 this 要添加方法的类名 自定义变量名
    //逗号后为第二个参数
    public static void PrintSelfAndNum(this string str,int num)
    {
        Console.WriteLine(str+num);
    }


}





class Program
{
    static void Main(string[] args)
    {
        string str="abc";

        str.PrintSelfAndNum(2);
        str.PrintSelfAndNum(3);

    }
}

你可能感兴趣的:(Unity)