C# 扩展方法注意事项

扩展方法注意事项

  1. 扩展方法所在的类必须是静态类。
  2. 扩展方法必须是静态方法。
  3. 扩展方法需要接受一个自身的参数:this。

下面是具体的一个例子:

class Program
    {
        static void Main(string[] args)
        {
            string str = "string";
            int i = str.str2int();//调用
            Console.WriteLine(i);
            Console.ReadLine();
        }
    }

    //扩展方法所在的类必须是静态类。
    static class CommonUtil
    {

        //扩展方法必须是静态方法。
        //扩展方法需要接受一个自身的参数:this
        public static int str2int(this string str)
        {
            int i;
            int.TryParse(str,out i);
            return i;
        }

    }