将代码行作为参数传递给函数

Passing line of code as argument into function

我希望将一行代码传递到我在 c# 中调用的函数中,目的是优化我的代码并尝试学习新的东西。正如我在代码中所示,我熟悉使用字符串、整数、浮点数和布尔值。

想法是在单击停止脚本并再次开始脚本的按钮时调用一个函数。没有该功能,此代码正在运行:

public void PlayOnClick()
{
    if(count != 1)
    {
        m_animator.GetComponent<Animator>().Play("Scale");
        d_animator.GetComponent<Animator>().Play("CloseUp");
        ((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Play();
        Dialyser.GetComponent<RotationByMouseDrag>().enabled = false;
        count = 1;
    }
    else
    {
        m_animator.GetComponent<Animator>().Play("Scale");
        d_animator.GetComponent<Animator>().Play("ScaleDown");
        ((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Stop();
        Dialyser.GetComponent<RotationByMouseDrag>().enabled = true;
        count = 0;
    }     
}

不过我相信这可以缩短。到目前为止我得到了这个:

void Lock(string A, string B, ? C, bool D, int E)
{
    m_animator.GetComponent<Animator>().Play(A);
    d_animator.GetComponent<Animator>().Play(B);
    C;
    Dialyser.GetComponent<RotationByMouseDrag>().enabled = D;
    count = E;

}

在函数 C 中,我想在按下一次时传递以下行:

((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Stop();

再次按下时将其更改为:

((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Play();

我遇到过 eval - 但我相信这仅适用于 javascript 并且可能会占用大量处理器资源。我已经研究过将该行解析为字符串。

我目前在搜索和尝试上都胜出。谁能帮我解释一下这个问题?

您必须传递 Action 类型或自定义委托:

void Lock(string A, string B, System.Action C, bool D, int E)
{
    m_animator.GetComponent<Animator>().Play(A);
    d_animator.GetComponent<Animator>().Play(B);
    C();
    Dialyser.GetComponent<RotationByMouseDrag>().enabled = D;
    count = E;    
}

// ...

Lock("Scale", "CloseUp", ((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Play, false, 1 ) ;

您要找的是委托,或者用 C++ 术语来说就是函数指针。

您可以在 delegates 此处找到更多信息。

Actions 可能感觉用它编码更快。

基本上,您可以传递对要执行的方法的引用。方法的签名应与方法中声明的参数类型完全相同。因此,如果您希望传递 运行 一段没有 return 任何值的代码,您可以使用 Action 类型,而无需任何类型参数。例如

class A {
    void printAndExecute(String textToPrint, Action voidMethodToExecute) {
        Debug.Log(textToPrint);
        voidMethodToExecute();
    }
}

class B : MonoBehaviour {
    void Start() {
        new A().printAndExecute("SAY", sayHello);
    }

    void sayHello() {
        Debug.Log("Hello!");
    }
}

希望对您有所帮助