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.扩展方法可以带参数

  • 相关阅读:
    重启进程
    linux如何查看端口被哪个进程占用?
    Web服务器磁盘满深入解析及解决
    基于Nginx实现访问控制、连接限制
    Tomcat线程模型分析及源码解读
    linux防火墙使用以及配置
    MySQL死锁及解决方案
    tcpdump 命令
    netperf 网络性能测试
    netstat 命令详解
  • 原文地址:https://www.cnblogs.com/mdnx/p/2745455.html
Copyright © 2011-2022 走看看