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
热门推荐
4 万寿祝福语简短
10 简短朋友旅行祝福语大全
11 永远漂亮祝福语女生简短
12 信耶稣的人祝福语简短
13 订婚新发言简短祝福语
14 妈妈祝福语简短16字
15 身体康复的祝福语简短
16 农民朋友发财祝福语简短
17 形容新年的祝福语简短
18 学生节祝福语大全简短