您的位置:首页 > 编程语言 > C#

C#温故而知新学习系列之面向对象编程—扩展方法(十)

2012-01-31 17:06 417 查看
  扩展方法

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

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

  创建扩展方法

  扩展方法和一般静态方法定义类似,惟一的区别是在第一个参数的前面加上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();
  }
  }
  }

  运行效果图

  


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐