当前位置: 移动技术网 > IT编程>开发语言>c# > 解析C#的扩展方法

解析C#的扩展方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

 在使用面向对象的语言进行项目开发的过程中,较多的会使用到“继承”的特性,但是并非所有的场景都适合使用“继承”特性,在设计模式的一些基本原则中也有较多的提到。

    继承的有关特性的使用所带来的问题:对象的继承关系实在编译时就定义好了,所以无法在运行时改变从父类继承的实现。子类的实现与它父类有非常紧密的依赖关系,以至于父类实现中的任何变化必然会导致子类发生变化。当你需要复用子类时,如果继承下来的实现不适合解决新的问题,则父类必须重写它或被其他更适合的类替换,这种依赖关系限制了灵活性并最终限制了复用性。替代继承特性的方式,较多的会采用 合成/聚合复用原则,“合成/聚合复用原则”:尽量使用合成/聚合,尽量不要使用类继承。

    如果在新类型的对象应当携带有关额外行为的细节,在使用继承特性时,有时可能不太适合,例如:处理指类型,密封类,或者接口时。在面对这些要求时,我们有时候会写一些静态类包含一些静态方法。但是过多的静态方法会造成额外的不必要的开销。

一.扩展方法概述:

    面对以上的有关“继承”的问题,以及在面对项目的一些需求时,我们需要解决这些问题的方式就是“扩展方法”。在c#3.0中引入了“扩展方法”,既有静态方法的优点,又使调用它们的代码的可读性得到了提高。在使用扩展方法时,可以像调用实例方法那样调用静态方法。

   1.扩展方法的基本原则:

      (1).c#只支持扩展方法,不支持扩展属性、扩展事件、扩展操作符等。

      (2).扩展方法(第一个参数前面是this的方法)必须在非泛型的静态类中声明,扩展方法必须有一个参数,而且只有第一个参数使用this标记。

      (3).c#编译器查找静态类中的扩展方法时,要求这些静态类本身必须具有文件作用域。

      (4).c#编译要求“导入”扩展方法。(静态方法可以任意命名,c#编译器在寻找方法时,需要花费时间进行查找,需要检查文件作用域中的所有的静态类,并扫描它们的所有静态方法来查找一个匹配)

      (5).多个静态类可以定义相同的扩展方法。

      (6).用一个扩展方法扩展一个类型时,同时也扩展了派生类型。

   2.扩展方法声明:

     (1).必须在一个非嵌套的、非泛型的静态类中(所以必须是一个静态方法)

     (2).至少有一个参数。

     (3).第一个参数必须附加this关键字做前缀。

     (4).第一个参数不能有其他任何修饰符(如ref或out)。

     (5).第一个参数的类型不能是指针类型。

 以上的两个分类说明中,对扩展方法的基本特性和声明方式做了一个简单的介绍,有关扩展方法的使用方式,会在后面的代码样例中进行展示,再次就不再多做说明。

二.扩展方法原理解析:

    “扩展方法”是c#独有的一种方法,在扩展方法中会使用extensionattribute这个attribute。

    c#一旦使用this关键字标记了某个静态方法的第一个参数,编译器就会在内部向该方法应用一个定制的attribute,这个attribute会在最终生成的文件的元数据中持久性的存储下来,此属性在system.core dll程序集中。

    任何静态类只要包含了至少一个扩展方法,它的元数据中也会应用这个attribute,任何一个程序集包含了至少一个符合上述特点的静态类,它的元数据也会应用这个attribute。如果代码用了一个不存在的实例方法,编译器会快速的扫描引用的所有程序集,判断它们哪些包含了扩展方法,然后,在这个程序集中,可以扫描包含了扩展方法的静态类。

    如果同一个命名空间中的两个类含有扩展类型相同的方法,就没有办法做到只用其中一个类中的扩展方法。为了通过类型的简单名称(没有命名空间前缀)来使用类型,可以导入该类型所有在的命名空间,但这样做的时候,你没有办法阻止那个命名空间中的扩展方法也被导入进来。

三..net3.5的扩展方法enumerable和queryable:

   在框架中,扩展方法最大的用途就是为linq服务,框架提供了辅助的扩展方法,位于system.linq命名空间下的enumerable和queryable类。enumerable大多数扩展是ienumerable<t>,queryable大多数扩展是iqueryable<t>。

   1.enumerable类中的常用方法:

      (1).range():一个参数是起始数,一个是要生成的结果数。

  public static ienumerable<int> range(int start, int count) { 
   long max = ((long)start) + count - 1;
   if (count < 0 || max > int32.maxvalue) throw error.argumentoutofrange("count"); 
   return rangeiterator(start, count);
  }
  static ienumerable<int> rangeiterator(int start, int count) { 
   for (int i = 0; i < count; i++) yield return start + i;
  }

 (2).where():对集合进行过滤的一个方式,接受一个谓词,并将其应用于原始集合中的每个元素。

 public static ienumerable<tsource> where<tsource>(this ienumerable<tsource> source, func<tsource, bool> predicate) {
   if (source == null) throw error.argumentnull("source"); 
   if (predicate == null) throw error.argumentnull("predicate"); 
   if (source is iterator<tsource>) return ((iterator<tsource>)source).where(predicate);
   if (source is tsource[]) return new wherearrayiterator<tsource>((tsource[])source, predicate); 
   if (source is list<tsource>) return new wherelistiterator<tsource>((list<tsource>)source, predicate);
   return new whereenumerableiterator<tsource>(source, predicate);
  }
  public whereenumerableiterator(ienumerable<tsource> source, func<tsource, bool> predicate) { 
    this.source = source;
    this.predicate = predicate; 
   }

以上分别介绍了range()和where()两个方法,该类中还主要包含select()、orderby()等等方法。

  2.queryable类中的常用方法:

 (1).iqueryable接口:

 /// <summary>
 /// 提供对未指定数据类型的特定数据源的查询进行计算的功能。
 /// </summary>
 /// <filterpriority>2</filterpriority>
 public interface iqueryable : ienumerable
 {
 /// <summary>
 /// 获取与 <see cref="t:system.linq.iqueryable"/> 的实例关联的表达式目录树。
 /// </summary>
 /// 
 /// <returns>
 /// 与 <see cref="t:system.linq.iqueryable"/> 的此实例关联的 <see cref="t:system.linq.expressions.expression"/>。
 /// </returns>
 expression expression { get; }
 /// <summary>
 /// 获取在执行与 <see cref="t:system.linq.iqueryable"/> 的此实例关联的表达式目录树时返回的元素的类型。
 /// </summary>
 /// 
 /// <returns>
 /// 一个 <see cref="t:system.type"/>,表示在执行与之关联的表达式目录树时返回的元素的类型。
 /// </returns>
 type elementtype { get; }
 /// <summary>
 /// 获取与此数据源关联的查询提供程序。
 /// </summary>
 /// 
 /// <returns>
 /// 与此数据源关联的 <see cref="t:system.linq.iqueryprovider"/>。
 /// </returns>
 iqueryprovider provider { get; }
 }

(2).where():

 public static iqueryable<tsource> where<tsource>(this iqueryable<tsource> source, expression<func<tsource, bool>> predicate) { 
   if (source == null)
    throw error.argumentnull("source"); 
   if (predicate == null)
    throw error.argumentnull("predicate");
   return source.provider.createquery<tsource>(
    expression.call( 
     null,
     ((methodinfo)methodbase.getcurrentmethod()).makegenericmethod(typeof(tsource)), 
     new expression[] { source.expression, expression.quote(predicate) } 
     ));
  }

 (3).select():

  public static iqueryable<tresult> select<tsource,tresult>(this iqueryable<tsource> source, expression<func<tsource, tresult>> selector) {
   if (source == null)
    throw error.argumentnull("source");
   if (selector == null) 
    throw error.argumentnull("selector");
   return source.provider.createquery<tresult>( 
    expression.call( 
     null,
     ((methodinfo)methodbase.getcurrentmethod()).makegenericmethod(typeof(tsource), typeof(tresult)), 
     new expression[] { source.expression, expression.quote(selector) }
     ));
  }

   以上是对扩展方法中两个类进行了一个简单的解析。

四.扩展方法实例:

   由于扩展方法实际是对一个静态方法的调用,所以clr不会生成代码对调用方法的表达式的值进行null值检查

   1.异常处理代码:

 /// <summary>
 /// 为参数验证提供有用的方法
 /// </summary>
 public static class argumentvalidator
 {
  /// <summary>
  /// 如果argumenttovalidate为空,则抛出一个argumentnullexception异常
  /// </summary>
  public static void throwifnull(object argumenttovalidate, string argumentname)
  {
   if (null == argumentname)
   {
    throw new argumentnullexception("argumentname");
   }
   if (null == argumenttovalidate)
   {
    throw new argumentnullexception(argumentname);
   }
  }
  /// <summary>
  /// 如果argumenttovalidate为空,则抛出一个argumentexception异常
  /// </summary>
  public static void throwifnullorempty(string argumenttovalidate, string argumentname)
  {
   throwifnull(argumenttovalidate, argumentname);
   if (argumenttovalidate == string.empty)
   {
    throw new argumentexception(argumentname);
   }
  }
  /// <summary>
  /// 如果condition为真,则抛出argumentexception异常
  /// </summary>
  /// <param name="condition"></param>
  /// <param name="msg"></param>
  public static void throwiftrue(bool condition, string msg)
  {
   throwifnullorempty(msg, "msg");
   if (condition)
   {
    throw new argumentexception(msg);
   }
  }
  /// <summary>
  /// 如果指定目录存在该文件则抛出filenotfoundexception异常
  /// </summary>
  /// <param name="filesytemobject"></param>
  /// <param name="argumentname"></param>
  public static void throwifdoesnotexist(filesysteminfo filesytemobject, string argumentname)
  {
   throwifnull(filesytemobject, "filesytemobject");
   throwifnullorempty(argumentname, "argumentname");
   if (!filesytemobject.exists)
   {
    throw new filenotfoundexception("'{0}' not found".fi(filesytemobject.fullname));
   }
  }
  public static string fi(this string format, params object[] args)
  {
   return formatinvariant(format, args);
  }
  /// <summary>
  /// 格式化字符串和使用<see cref="cultureinfo.invariantculture">不变的文化</see>.
  /// </summary>
  /// <remarks>
  /// <para>这应该是用于显示给用户的任何字符串时使用的“b”>“b”>“”。它意味着日志
  ///消息,异常消息,和其他类型的信息,不使其进入用户界面,或不会
  ///无论如何,对用户都有意义;).</para>
  /// </remarks>
  public static string formatinvariant(this string format, params object[] args)
  {
   throwifnull(format, "format");
   return 0 == args.length ? format : string.format(cultureinfo.invariantculture, format, args);
  }
  /// <summary>
  /// 如果时间不为datetimekind.utc,则抛出argumentexception异常
  /// </summary>
  /// <param name="argumenttovalidate"></param>
  /// <param name="argumentname"></param>
  public static void throwifnotutc(datetime argumenttovalidate, string argumentname)
  {
   throwifnullorempty(argumentname, "argumentname");
   if (argumenttovalidate.kind != datetimekind.utc)
   {
    throw new argumentexception("you must pass an utc datetime value", argumentname);
   }
  }
 }

    2.枚举扩展方法:

 public static class enumextensions
 {
  /// <summary>
  /// 获取名字
  /// </summary>
  /// <param name="e"></param>
  /// <returns></returns>
  public static string getname(this enum e)
  {
   return enum.getname(e.gettype(), e);
  }
  /// <summary>
  /// 获取名字和值
  /// </summary>
  /// <param name="enumtype">枚举</param>
  /// <param name="lowerfirstletter">是否转化为小写</param>
  /// <returns></returns>
  public static dictionary<string, int> getnamesandvalues( this type enumtype, bool lowerfirstletter)
  {
   //由于扩展方法实际是对一个静态方法的调用,所以clr不会生成代码对调用方法的表达式的值进行null值检查
   argumentvalidator.throwifnull(enumtype, "enumtype");
   //获取枚举名称数组
   var names = enum.getnames(enumtype);
   //获取枚举值数组
   var values = enum.getvalues(enumtype);
   var d = new dictionary<string, int>(names.length);
   for (var i = 0; i < names.length; i++)
   {
    var name = lowerfirstletter ? names[i].lowerfirstletter() : names[i];
    d[name] = convert.toint32(values.getvalue(i));
   }
   return d;
  }
  /// <summary>
  /// 转换为小写
  /// </summary>
  /// <param name="s"></param>
  /// <returns></returns>
  public static string lowerfirstletter(this string s)
  {
   argumentvalidator.throwifnull(s, "s");
   return char.tolowerinvariant(s[0]) + s.substring(1);
  }
 }

    五.总结:

    在本文中,主要对扩展方法进行了一些规则说明、声明方式,使用方式,以及对扩展方法的意义和扩展方法的原理进行了简单的解答。并在本文的最后给了一个枚举的扩展方法代码。

以上就是本文的全部内容,希望对大家有所帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网