C# 之 扩展方法
发布时间:2020-12-13 20:22:57 所属栏目:PHP教程 来源:网络整理
导读:扩大方法 扩大方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩大方法是1种特殊的静态方法,但可以像扩大类型上的实例方法1样进行调用。对用 C# 和 Visual Basic 编写的客户端代码,调用扩大方法与调用在
扩大方法 扩大方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩大方法是1种特殊的静态方法,但可以像扩大类型上的实例方法1样进行调用。对用 C# 和 Visual Basic 编写的客户端代码,调用扩大方法与调用在类型中实际定义的方法之间没有明显的差异。 如果我们有这么1个需求,将1个字符串的第1个字符转化为大写,第2个字符到第n个字符转化为小写,其他的不变,那末我们该如何实现呢?
不使用扩大方法: <span style="font-size:10px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExtraMethod
{
//抽象出静态StringHelper类
public static class StringHelper
{
//抽象出来的将字符串第1个字符大写,从第1个到第len个小写,其他的不变的方法
public static string ToPascal(string s,int len)
{
return s.Substring(0,1).ToUpper() + s.Substring(1,len).ToLower() + s.Substring(len + 1);
}
}
class Program
{
static void Main(string[] args)
{
string s1 = "aSDdAdfGDFSf";
string s2 = "sbfSDffsjG";
Console.WriteLine(StringHelper.ToPascal(s1,3));
Console.WriteLine(StringHelper.ToPascal(s2,5));
}
}
}</span> 使用扩大方法: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExtraMethod
{
class Program
{
static void Main(string[] args)
{
string s1 = "aSDdAdfGDFSf";
string s2 = "sbfSDffsjG";
Console.WriteLine(s1.ToPascal(3));
Console.WriteLine(s2.ToPascal(5));
}
}
//扩大类,只要是静态就能够
public static class ExtraClass
{
//扩大方法--特殊的静态方法--为string类型添加特殊的方法ToPascal
public static string ToPascal(this string s,len).ToLower() + s.Substring(len + 1);
}
}
}
通过上面两种方法的比较: 1.代码在访问ToPascal这样的静态方法时更加便捷。用起来就像是被扩大类型确切具有该实例方法1样。 2.扩大方法不改变被扩大类的代码,不用重新编译、修改、派生被扩大类 定义扩大方法
注意事项: 1.扩大方法必须在静态类中定义 2.扩大方法的优先级低于同名的类方法 3.扩大方法只在特定的命名空间内有效 4.除非必要不要滥用扩大方法 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |