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

  • 相关阅读:
    【Python】使用hashlib进行MD5和sha1摘要计算
    【Python】torrentParser1.04 增加获得磁力链URI功能
    day30_Hibernate复习_02
    day30_Hibernate学习笔记_02
    day29_Hibernate复习_01
    day29_Hibernate学习笔记_01
    【重要】Spring在web.xml中的配置原理说明
    HTTP常见错误编号
    一级缓存和二级缓存的理解
    电商网站前台与后台系统架构
  • 原文地址:https://www.cnblogs.com/mdnx/p/2745455.html
Copyright © 2011-2022 走看看