版权属于:
一缕清风_一个分享心得的网站_程序员_个人博客
作品采用:
《
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
》许可协议授权
通常c#扩展方法被定义为静态方法,若不想在原有的类或者对象中进行修改,额外定义扩展方法是一个不错的选择。
本文以string为例子,定义一个判断字符串是否为空的扩展方法。
class Program
{
static void Main(string[] args)
{
string demo = "mydemotext";
//调用扩展方法
if (demo.IsEmpty())
{
Console.WriteLine("字符串为空");
}
else
{
Console.WriteLine("字符串不为空");
}
Console.ReadKey();
}
}
/// <summary>
/// 定义扩展方法
/// </summary>
public static class DemoExtenison
{
public static bool IsEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
}
运行结果
评论 (0)