1. 程式人生 > 實用技巧 >U3d:關於對方法的鏈式擴充套件

U3d:關於對方法的鏈式擴充套件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test7 : MonoBehaviour
{

    public GameObject go;
    // Start is called before the first frame update
    void Start()
    {
        go.Show()
            .Hide()
            .Name("aa");


    }

    // Update is called once per frame
void Update() { } } public static class GameObjectExtension { public static GameObject Show(this GameObject selfObject) { selfObject.SetActive(true); return selfObject; } public static GameObject Hide(this GameObject selfObject) { selfObject.SetActive(
false); return selfObject; } public static GameObject Name(this GameObject selfObject, string str) { selfObject.name = str; return selfObject; } }

擴充套件方法被定義為靜態方法,但它們是通過例項方法語法進行呼叫的。它們的第一個引數指定該方法作用於哪個型別,並且該引數以 this 修飾符為字首。僅當您使用 using 指令將名稱空間顯式匯入到原始碼中之後,擴充套件方法才位於範圍中。