zoukankan      html  css  js  c++  java
  • C#类(16) 扩展方法

    ExtensionProcedure.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    //扩展方法的声明方式 :  修饰符 static 返回类型 方法名 (this 需要添加方法的类 参数名 , 参数列表)如下:


    public static void Extension (this String s , string value)
    namespace ConsoleApplication1 { public static class ExtensionProcedure // 扩展方法必须声明在静态类中 { //给String类添加一个方法. public static string ShowValue(this String y, string value) { return value; } //给下面那个MyClass类添加一个方法, public static int Age(this MyClass M, int value) { return value; } } public class MyClass { } }

               

    Program.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string str = null;
                str = str.ShowValue("Tony");
                Console.WriteLine(str);
               
                MyClass my = new MyClass();
                int age = my.Age(19);
                Console.WriteLine(age.ToString());
    
            }
        }
    }
    //扩展方法的特点


    // 1. 扩展方法是给现有的类添加一个方法。
    // 2. 扩展方法是通过指定关键字this修饰方法的第一个参数 , 且必须是静态方法。
    // 3. 扩展方法必须声明在静态类中。
    // 4. 扩展方法要通过对象来调用,虽然定义的时静态方法。
    // 5.扩展方法可以带参数

  • 相关阅读:
    nginx配置ssl并结局TP3.2路由pathinfo
    TP3.2公共模板
    linux 上mysql慢日志查询
    RBAC流程
    Linux下安装Lnmp环境
    php操作redis命令大全
    Opencv无法调用cvCaptureFromCAM无法打开电脑自带摄像头
    c++考研复习之非递归前序中序后序遍历二叉树
    学习《Numpy基础知识》
    学习《Numpy快速教程
  • 原文地址:https://www.cnblogs.com/mdnx/p/2745455.html
Copyright © 2011-2022 走看看