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

  • 相关阅读:
    Redis教程_2
    Redis教程_1
    机器学习概念_2
    机器学习概念_1
    [极客大挑战 2019]LoveSQL
    [极客大挑战 2019]EasySQL
    [SUCTF 2019]EasySQL
    [强网杯 2019]随便注
    [HCTF 2018] WarmUp
    php代码函数笔记
  • 原文地址:https://www.cnblogs.com/mdnx/p/2745455.html
Copyright © 2011-2022 走看看