作为C#程序员,我们一直要跟自带类库(BCL - Base class Library)或者第三方类库打dao交道,有时候我们无法查看他们的代码,但是我们需要一些新的功能,Helper类就应运而生了,我们开发出一个个的静态方法以方便调用,C#3.0之后微软为我们提供了扩展类,以实现对原有类的扩展,这是一个非常好的替代Helper类的途径。 扩展类和扩展方法的使用方法 首先举一个扩展类的例子,假定我们需要string类实现一个新的功能,通过属性名字获取属性的值,我们可以通过扩展类的扩展方法实现。
///
/// 扩展类和扩展方法必须是静态的,扩展方法的第一个参数必须为原有类自身,this关键字是必须的
///
public static class StringExtension
{
public static object GetValueByName(this object self, string propertyName)
{
if (self == null)
{
return self;
}
Type t = self.GetType();
PropertyInfo p = t.GetProperty(propertyName);
return p.GetValue(self, null);
}
}
原有类可以直接调用扩展方法,
string str = "123";
int len = str.GetValueByName("Length");
怎么样,方便吧。 扩展方法必须遵守以下规则: 1.扩展类必须是静态的; 2.扩展方法必须是静态的 3.扩展方法的第一个参数必须以this开头,参数必须是原有类的类型,如果我们扩展decimal类,第一个参数必须为decimal 为什么扩展类和扩展方法必须为静态的 让我们看一看编译之后的MSIL代码吧,是不是很像我们曾经写过的Helper类调用方法,看来str.GetValueByName("Length")等效于StringExtension.GetValueByName(str,"Length"). 这是微软对编译器做的一个优化,使之更人性化,使用更方便。微软的出发点可能只是希望对原有类做方法扩展,不希望把扩展类作为实体类来使用,所以从设计上就已经做了处理,杜绝这种情况发生,静态类是不允许被实例化的。
我们要给string对象加一个扩展方法(注意这个方法不能和调用的Main方法放在同一个类中):
public static string GetNotNullStr(this string strRes)
{
if (strRes == null)
return string.Empty;
else
return strRes ;
}
然后在Main方法里面调用:
static void Main(string[] args)
{
string strTest = null;
var strRes = strTest.GetNotNullStr();
}
public static string GetNotNullStr(this string strRes)其中this string就表示给string对象添加扩展方法。
那么在同一个命名空间下面定义的所有的string类型的变量都可以.GetNotNullStr()这样直接调用。
strTest.GetNotNullStr();为什么这样调用不用传参数,是因为strTest就是作为参数传入到方法里面的。你可以试试。使用起来就和.Net framework定义的方法一样:
https://www.cnblogs.com/zhang1f/p/11106081.html
https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/extension-methods