zoukankan      html  css  js  c++  java
  • C#_扩展方法

    //当一个类不能再修改时,需要添加其他额外的方法---》扩展方法

    步骤:1.创建一个静态类  保证该类与要扩展的类在同一个命名空间下

       2.在静态类中创建静态方法  标记静态方法的参数  (this 类型 ob)  this 必不可少  类型为要扩展的类型  ob为将来要引用该扩展方法的对象

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace _13扩展方法练习
     8 {
     9     /// <summary>
    10     /// Date:2015-11-26
    11     /// Author:Xuqingchi
    12     /// Version:vs2012
    13     /// </summary>
    14     class Program
    15     {
    16         static void Main(string[] args)
    17         {
    18 
    19             //第一步: 创建静态类  
    20             //第二步: 创建静态方法(this TestClass ob)
    21             TestClass tc1=new TestClass(){Id="Xuqingchi"};
    22             tc1.DoSth();
    23 
    24             //调用扩展方法
    25             tc1.DoSthElse();
    26 
    27         }
    28     }
    29 
    30      public class TestClass
    31     {
    32 
    33         private string _id;
    34 
    35         public string Id
    36         {
    37           get { return _id; }
    38           set { _id = value; }
    39         }
    40 
    41          public  void DoSth()
    42          {
    43              Console.WriteLine("testClass do sth...");
    44          }
    45 
    46     }
    47 }
    调用扩展方法
    namespace _13扩展方法练习
    {
        static class Class1
        {
            //该静态方法的第一个参数  this 是必须得 扩展的对象  obj就表示将来要调用此方法的对象 
            public static void DoSthElse(this TestClass o)
            {
                Console.WriteLine("Do Sth else .^_~ .   {0}",o.Id);
            }
        }
    }
    创建的静态类
  • 相关阅读:
    Centos 下oracle 11g 安装部署及手动建库过程
    MongoDB 存储引擎Wiredtiger原理剖析
    有关RDS上只读实例延时分析-同适用于自建MySQL主从延时分析判断
    windows 下my.ini的配置优化
    什么是purge操作
    linux内核调优参考
    通过第三方镜像仓库代理下载镜像
    微积分拾遗——链式法则
    Java中的RASP实现
    机器学习是什么
  • 原文地址:https://www.cnblogs.com/siyi/p/4998883.html
Copyright © 2011-2022 走看看