gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:54:04 24 4
gpt4 key购买 nike

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

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

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,并且可能会占用大量处理器资源。我研究过将该行解析为字符串。

我目前在搜索和尝试方面都胜出。任何人都可以为我阐明这一点吗?

最佳答案

您正在寻找的是委托(delegate),或者用 C++ 术语来说是函数指针。

您可以在 delegates 上找到更多信息这里。

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

基本上,您可以传递对要执行的方法的引用。方法的签名应与方法中声明的参数类型完全相同。因此,如果您希望传递并运行一段不返回任何值的代码,您可以使用不带任何类型参数的 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!");
}
}

希望对你有帮助

关于c# - 将代码行作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43999429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com