扩展方法

扩展方法是你能够向现有类型和自定义类型添加方法,而无需创建新的派生类型或者以其他方式修改原始类型

  扩展方法是一个特殊的静态方法,它定义在一个静态类中,但是可以在其他类型(我们要扩展的那个类)的对象上像调用实例方法那样调用,因此通过扩展方法可以在不修改一个类的前提下对一个类进行功能上的补充

  创建扩展方法

  扩展方法和一般静态方法定义类似,惟一的区别是在第一个参数的前面加上this关键字,同时第一个参数的类型也决定了扩展方法可以扩展的类型

  格式

  public static 返回类型 扩展方法名称(this 要扩展的类型sourceObj[,扩展方法参数列表])

  扩展方法的特点

  1:扩展方法是给现有类型添加一个方法

  2:扩展方法通过指定this关键字修饰方法的第一个参数

  3:扩展方法必须声明在静态类中

  4:扩展方法通过对象来调用

  5:扩展方法可以带参数

   实例

  using System;

  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  namespace _10_ExpandMethod
  {
      public static class AddClass
      {
          //扩展现有String类型
          public static string GetLower(this String str)
          {
              return str.ToLower();
          }
          //扩展自定义的Studengt类型
          public static string GetName(this Student stu,string strName)
          {
              return strName;
          }
      }

    //自定义的Student类型
      public class Student
      { 
        
      }

      class Program
      {
          static void Main(string[] args)
          {
              string strURL = "HTTP://WWW.BAIDU.COM";
              strURL = strURL.GetLower();
              Console.WriteLine(strURL);

              string strName = "小强";
              Student student = new Student();
              Console.WriteLine(student.GetName(strName));
              Console.ReadKey();
          }
      }
  }

  运行效果图

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值