zoukankan      html  css  js  c++  java
  • C#中扩展方法的使用

    MSDN中这样定义扩展方法:扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。 对于用 C#、F# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法没有明显区别。

    扩展方法第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀,下面是一个简单的扩展方法实现

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public static class Extension {
        public static void CleanChild(this Transform tran) {
            foreach (Transform trans in tran)
            {
                UnityEngine.Object.Destroy(trans.gameObject);
            }
        }
    }
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class TestExtension : MonoBehaviour {
        void Start () {
            transform.CleanChild();
        }
    }

    虽然像是调用实例方法一样调用,但其实是静态方法。

  • 相关阅读:
    To do list
    2020 上半学期比赛记录
    板子
    Project Euler 1~10 野蛮题解
    卡常火车头
    防止unordered_map 被卡方法
    2019 香港区域赛 BDEG 题解
    2019徐州区域赛 ACEFM 题解 & pollard-rho & miller-rabin & 求出每个子树的重心 板子
    BST-splay板子
    ZJOI2017(2) 游记
  • 原文地址:https://www.cnblogs.com/Mr147/p/9876717.html
Copyright © 2011-2022 走看看