您的位置:首页 > 编程语言 > C#

c# 扩展方法奇思妙用基础:string 常用扩展

2015-06-15 18:43 696 查看
string是c#里面最最常用的类,和它的使用频度比起来,它的操作确少的可怜,实例方法只有三十个左右,静态方法只有十多个,远远满足不了我们日常的需求。

本文使用扩展方法来增加string的功能,举出几个例子,也算是抛砖引玉吧!

首先我们把string类最常用的静态方法IsNullOrEmpty扩展成“实例”方法:

public static bool IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s);
}


下面是调用代码:

public static void Test1()
{
string s = "";
bool b1 = string.IsNullOrEmpty(s);
bool b2 = s.IsNullOrEmpty();
}


别小看这一步改进,扩展后可减少我们编写代码的时间,提高我们编码的速度。如你对此怀疑,将第4行和第5行的代码手工录入100次(不能复制粘贴)试试,就知道了!

如果你需要,也可以扩展出“IsNotNullOrEmpty”。

再来看下FormatWith扩展

public static string FormatWith(this string format, params object[] args)
{
return string.Format(format, args);
}
public static void Test2()
{
string today = "今天是:{0:yyyy年MM月dd日 星期ddd}".FormatWith(DateTime.Today);
}


也很简单的,我们这里简单说一下效率问题,string.Format函数有多个重载:

public static string Format(string format, params object[] args);
public static string Format(string format, object arg0);
public static string Format(string format, object arg0, object arg1);
public static string Format(string format, object arg0, object arg1, object arg2);
public static string Format(IFormatProvider provider, string format, params object[] args);


尽管第1行的Format功能强大到可以取代中间的三个,但它的效率不高。中间三个重载是出于性能的考虑。

如果你比较看重效率的性能,仅仅使用一个FormatWith扩展是不行的,可以参照Format的重载,多扩展上几个!

.Net中处理字符串最强大的还是正则表达式,下面我们将其部分功能扩展至string上:

public static bool IsMatch(this string s, string pattern)
{
if (s == null) return false;
else return Regex.IsMatch(s, pattern);
}

public static string Match(this string s, string pattern)
{
if (s == null) return "";
return Regex.Match(s, pattern).Value;
}

public static void Test3()
{
bool b = "12345".IsMatch(@"\d+");
string s = "ldp615".Match("[a-zA-Z]+");
}


使用Regex要引用命名空间“System.Text.RegularExpressions”。

扩展后,我们就可以直接使用扩展中的方法,而不必再引用这个命名空间了,也不用写出“Regex”了。

Regex的Replace方法也比较常用,也可以扩展到string上。

接下来是与int相关的操作:

public static bool IsInt(this string s)
{
int i;
return int.TryParse(s, out i);
}

public static int ToInt(this string s)
{
return int.Parse(s);
}

public static void Test4()
{
string s = "615";
int i = 0;
if (s.IsInt()) i = s.ToInt();
}


同样方法可完成转换到DateTime。

如果你用过CodeSmith,对下面这种应用应该比较熟悉:

public static string ToCamel(this string s)
{
if (s.IsNullOrEmpty()) return s;
return s[0].ToString().ToLower() + s.Substring(1);
}

public static string ToPascal(this string s)
{
if (s.IsNullOrEmpty()) return s;
return s[0].ToString().ToUpper() + s.Substring(1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: