zoukankan      html  css  js  c++  java
  • 方法的扩展之使用静态方法

    如何扩展方法:

    1.如果有源代码,直接添加新方法;

    2.如果不能修改但也不是密封类,可以派生子类扩展;

    3.如果以上条件都不满足,可以使用静态类扩展方法。

    关于静态类扩展方法示例如下:

            static void Main(string[] args)
            {
                Person person = new Person();
                person.Eat();//人类本身已有的吃方法
                person.Sleep();//静态类扩展的睡觉方法
    
            }
        /// <summary>
        /// 扩展静态方法条件:
        /// 1 类是静态类,方法是静态方法
        /// 2 方法的第一个参数必须是this+该类名
        /// </summary>
        class Person
        {
            public void Eat()
            {
                Console.WriteLine("吃饭~");
            }
        }
    
        //2.0 扩展静态类
        static class PersonExtend
        {
            public static void Sleep(this Person person)
            {
                Console.WriteLine("睡觉~");
            }
        }

    如上,一开始人类只有一个吃的方法,后来如果要为人类添加一个睡觉的方法,可以使用静态扩展类。调用方式和调用类本身方法一样(看代码注释)。

    over!

  • 相关阅读:
    BluetoothGetRadioInfo 函数
    BluetoothFindRadioClose 函数
    BluetoothFindNextRadio 函数
    BluetoothFindFirstRadio 函数
    BLUETOOTH_DEVICE_INFO 函数
    BluetoothSetServiceState 函数
    Bluetooth Functions
    union联合体学习
    置顶
    Toppo: 1
  • 原文地址:https://www.cnblogs.com/Med1tator/p/6442315.html
Copyright © 2011-2022 走看看