源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C#扩展方法实例分析

  • 时间:2021-11-19 18:59 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#扩展方法实例分析
本文实例讲述了C#扩展方法。分享给大家供大家参考,具体如下: [b]扩展方法[/b] 扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。对于用 C# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法之间没有明显的差异。 如果我们有这么一个需求,将一个字符串的第一个字符转化为大写,第二个字符到第n个字符转化为小写,其他的不变,那么我们该如何实现呢? [b]不使用扩展方法:[/b]
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));
    }
  }
}

[img]http://files.jb51.net/file_images/article/201706/201761582926273.png?201751583159[/img] 使用扩展方法:
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);
    }
  }
}

[img]http://files.jb51.net/file_images/article/201706/201761583202534.png?20175158330[/img] [b]通过上面两种方法的比较:[/b]     1.代码在访问ToPascal这样的静态方法时更为便捷。用起来就像是被扩展类型确实具有该实例方法一样。     2.扩展方法不改变被扩展类的代码,不用重新编译、修改、派生被扩展类 [b]定义扩展方法[/b]     1.定义一个静态类以包含扩展方法。     2.该类必须对客户端代码可见。     3.将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。     4.方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。 请注意,第一个参数不是由调用代码指定的,因为它表示正应用运算符的类型,并且编译器已经知道对象的类型。 您只需通过 n 为这两个形参提供实参。 [b]注意事项:[/b]     1.扩展方法必须在静态类中定义     2.扩展方法的优先级低于同名的类方法     3.扩展方法只在特定的命名空间内有效     4.除非必要不要滥用扩展方法 更多关于C#相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/611.htm]C#窗体操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/116.htm]C#数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/165.htm]C#常见控件用法教程[/url]》、《[url=http://www.1sucai.cn/Special/478.htm]C#面向对象程序设计入门教程[/url]》及《[url=http://www.1sucai.cn/Special/227.htm]C#程序设计之线程使用技巧总结[/url]》 希望本文所述对大家C#程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部