Unity3d,C#传递函数作为参数
我有Unity3d,C#传递函数作为参数,c#,parameters,unity3d,delegates,C#,Parameters,Unity3d,Delegates,我有ScriptA和许多void函数: void methodOne() { some code } void methodTwo(int a, int b) { } 我想传递到另一个脚本的静态方法。让我们说它scriptB: ScriptB.staticMethod(methodOne, some, other, primitive, parameters); ScriptB.staticMethod(methodTwo(a, b), some, other, parameters
ScriptA
和许多void
函数:
void methodOne() {
some code
}
void methodTwo(int a, int b) {
}
我想传递到另一个脚本的静态方法。让我们说它scriptB
:
ScriptB.staticMethod(methodOne, some, other, primitive, parameters);
ScriptB.staticMethod(methodTwo(a, b), some, other, parameters);
我脚本的主要思想是
ScriptB
将从服务器获取数据,并调用从ScriptA
获取的方法,根据数据在我的游戏中进行更改。将这些方法作为参数时,是否需要启动它们?或者您需要这些方法中的值吗
无论是哪种方式,您都可以做两件事,或者只是将方法的名称作为字符串传递,然后在方法中检查输入的名称并在方法中启动该方法。将方法作为参数时是否需要启动方法?或者您需要这些方法中的值吗
无论采用哪种方法,您都可以做两件事,或者只是将方法的名称作为字符串传递,然后在方法中检查已输入的名称,并在方法中启动该方法。我不确定您在这里试图实现什么。 但要回答您的问题,您可以使用委托将方法作为参数传递。以下是一个例子:
public class ScriptA
{
public delegate void MethodOneDelegate(int a, int b);
public void MethodOne(int a, int b)
{
Console.WriteLine(a + b);
}
}
public static class ScriptB
{
public static void StaticMethod(ScriptA.MethodOneDelegate function, int a, int b)
{
function(a, b);
}
}
public static void Main()
{
ScriptA scriptA = new ScriptA();
ScriptB.StaticMethod(scriptA.MethodOne, 1, 2);
}
还有其他解决方案,您可以查看System.Func和System.Action。我不确定您在这里想要实现什么。 但要回答您的问题,您可以使用委托将方法作为参数传递。以下是一个例子:
public class ScriptA
{
public delegate void MethodOneDelegate(int a, int b);
public void MethodOne(int a, int b)
{
Console.WriteLine(a + b);
}
}
public static class ScriptB
{
public static void StaticMethod(ScriptA.MethodOneDelegate function, int a, int b)
{
function(a, b);
}
}
public static void Main()
{
ScriptA scriptA = new ScriptA();
ScriptB.StaticMethod(scriptA.MethodOne, 1, 2);
}
还有其他解决方案,您可以查看System.Func和System.Action。代码如何区分
MethodOneDelegate
是MethodOne
s?我想我需要赋值。MethodOneDelegate
只描述了MethodOne
的签名(取两个整数并返回void)。StaticMethod
将调用的方法作为参数(scriptA.MethodOne)提供。我可以在ScriptB
中声明delgates吗?它将类似于调用的模板。是的,当然可以在ScriptB
中声明MethodOneDelegate
,而不是ScriptA
。请添加指向System.Func和System.Action的链接。代码将如何区分MethodOneDelegate
是MethodOne
s?我想我需要赋值。MethodOneDelegate
只描述了MethodOne
的签名(取两个整数并返回void)。StaticMethod
将调用的方法作为参数(scriptA.MethodOne)提供。我可以在ScriptB
中声明delgates吗?它将类似于调用的模板。是的,当然可以在ScriptB
中声明MethodOneDelegate
,而不是ScriptA
。请添加指向System.Func和System.Action的链接