扩展方法注意事项

  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;
        }

    }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-15
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
  • 2022-03-07
  • 2022-12-23
猜你喜欢
  • 2021-09-21
  • 2022-12-23
  • 2021-08-13
  • 2022-12-23
相关资源
相似解决方案