假设我有两个功能:

void DoesNothing(){}

void OnlyCalledOnce(){
    //lines of code
}


可以调用OnlyCalledOnce并实际运行DoesNothing吗?我想象这样的事情:

void DoesNothing(){}

void OnlyCalledOnce(){
    //lines of code
    OnlyCalledOnce = DoesNothing;
}


在最后一行之后,每当我调用OnlyCalledOnce时,它将运行DoesNothing

可能吗?

最佳答案

您尝试使用委托吗?

class Program
{
    private static Action Call = OnlyCalledOnce;

    public static void Main(string[] args)
    {
        Call();
        Call();
        Call();
        Console.ReadKey();
    }

    static void DoesNothing()
    {
        Console.WriteLine("DoesNothing");
    }

    static void OnlyCalledOnce()
    {
        Console.WriteLine("OnlyCalledOnce");
        Call = DoesNothing;
    }
}

10-05 19:20