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

C#扩展方法实例分析

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

本文实例讲述了c#扩展方法。分享给大家供大家参考,具体如下:

扩展方法

扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。对于用 c# 和 visual basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法之间没有明显的差异。

如果我们有这么一个需求,将一个字符串的第一个字符转化为大写,第二个字符到第n个字符转化为小写,其他的不变,那么我们该如何实现呢?

不使用扩展方法:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
namespace extramethod
{
  //抽象出静态stringhelper类
  public static class stringhelper
  {
    //抽象出来的将字符串第一个字符大写,从第一个到第len个小写,其他的不变的方法
    public static string topascal(string s,int len)
    {
      return s.substring(0, 1).toupper() + s.substring(1, len).tolower() + s.substring(len + 1);
    }
  }
  class program
  {
    static void main(string[] args)
    {
      string s1 = "asddadfgdfsf";
      string s2 = "sbfsdffsjg";
      console.writeline(stringhelper.topascal(s1,3));
      console.writeline(stringhelper.topascal(s2, 5));
    }
  }
}

使用扩展方法:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
namespace extramethod
{
  class program
  {
    static void main(string[] args)
    {
      string s1 = "asddadfgdfsf";
      string s2 = "sbfsdffsjg";
      console.writeline(s1.topascal(3));
      console.writeline(s2.topascal(5));
    }
  }
  //扩展类,只要是静态就可以
  public static class extraclass
  {
    //扩展方法--特殊的静态方法--为string类型添加特殊的方法topascal
    public static string topascal(this string s, int len)
    {
      return s.substring(0, 1).toupper() + s.substring(1, len).tolower() + s.substring(len + 1);
    }
  }
}

通过上面两种方法的比较:

    1.代码在访问topascal这样的静态方法时更为便捷。用起来就像是被扩展类型确实具有该实例方法一样。
    2.扩展方法不改变被扩展类的代码,不用重新编译、修改、派生被扩展类

定义扩展方法

    1.定义一个静态类以包含扩展方法。
    2.该类必须对客户端代码可见。
    3.将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
    4.方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。

请注意,第一个参数不是由调用代码指定的,因为它表示正应用运算符的类型,并且编译器已经知道对象的类型。 您只需通过 n 为这两个形参提供实参。

注意事项:

    1.扩展方法必须在静态类中定义
    2.扩展方法的优先级低于同名的类方法
    3.扩展方法只在特定的命名空间内有效
    4.除非必要不要滥用扩展方法

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#窗体操作技巧汇总》、《c#数据结构与算法教程》、《c#常见控件用法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。

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

相关文章:

验证码:
移动技术网