C# 中的扩展方法

csharpprogrammingserver side programming

扩展方法是静态方法,它们被调用时就像是扩展类型上的实例方法一样。使用扩展方法,您可以向现有类型添加方法,甚至无需创建新的派生类型、重新编译或修改原始类型。

以下是我们创建的扩展方法。

public static int myExtensionMethod(this string str) {
   return Int32.Parse(str);
}

让我们看一个使用扩展方法的示例。

示例

using System;
using System.Text;
namespace Program {
   public static class Demo {
      public static int myExtensionMethod(this string str) {
         return Int32.Parse(str);
      }
   }
   class Program {
      static void Main(string[] args) {
         string str1 = "565";
         int n = str1.myExtensionMethod();
         Console.WriteLine("Result: {0}", n);
         Console.ReadLine();
      }
   }
}

输出

Result: 565

相关文章