C#中的扩展方法
扩展方法是静态方法,就像它们是扩展类型的实例方法一样被调用。使用扩展方法,您可以将方法添加到现有类型中,而无需创建新的派生类型,重新编译或修改原始类型。
以下是我们创建的扩展方法。
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