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


      扩展方法

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

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

      创建扩展方法

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

      运行效果图

      

      

    记录,成为更好的自己
  • 相关阅读:
    BRAFT EDITOR富文本编辑器
    小程序
    单元测试之道读书笔记(二)
    单元测试之道读书笔记(一)
    Blend学习网址
    2014年要读的10本书
    程序员一生必读的书籍
    WPF中PasswordBox控件无法绑定Password属性解决办法
    异步方式向WPF ListBox控件中一条一条添加记录
    10中适合编程的字体
  • 原文地址:https://www.cnblogs.com/menglin2010/p/2321402.html
Copyright © 2020-2023  润新知