引言
自从用上扩展方法以来,就欲罢不能了,它们大大提升了我的代码编写效率 ,现在我已对其产生了高度依赖。在此分享一下自己的常用扩展方法集,方便大 家使用。
示例
public static string ExpandAndToString(this System.Collections.IEnumerable s, string 间隔字符)
功能:将集合展开并分别执行ToString方法,再以指定的分隔符衔接,拼接 成一个字符串。
范例:
[TestMethod]
public void TestMethod1()
{
var i = new int[] {1,5,33,14,556 };
var Out="1-5-33-14-556";
Assert.AreEqual(Out,i.ExpandAndToString("-"));
}
public static bool IsNullOrEmpty(this string s)
功能:验证字符串对象是否为空对象或空字符串。
范例:
[TestMethod]
public void TestMethod2()
{
string s = null;
Assert.AreEqual(true,s.IsNullOrEmpty());
s += "123";
Assert.AreEqual(false, s.IsNullOrEmpty());
}
public static string IsNullOrEmptyThen(this string s, System.Func<string,string> 表达式)
功能:验证字符串对象是否为空对象或空字符串,如果是的话,则执行传入 表达式,并将表达式结果返回。
范例:
[TestMethod]
public void TestMethod3()
{
var s = "";
var Out = "1234";
Assert.AreEqual(Out, s.IsNullOrEmptyThen(f=>"1234"));
}