通常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);
}
}
运行结果