gpt4 book ai didi

java - 函数分类方法 : Switch-case, 或字典哪个更好?

转载 作者:行者123 更新时间:2023-12-02 03:09:30 25 4
gpt4 key购买 nike

[编辑:尽管鼓励提供有关 javaC# 的具体答案,但下面的代码示例与语言无关。]

在我的游戏中,存在一种情况,代码使用动态参数值(来自其他地方)来决定从多个候选函数中调用哪个函数。像这样的东西:

string theParam = parameterFromSomewhereElse;
if(theParam == "apple")
callingFunctionFor_apple();
else if(theParam == "banana")
callingFunctionFor_banana();
else if(theParam == "cat")
callingFunctionFor_cat();

显然,一种方法是上面提到的 if-else,甚至更干净的 switch-case,但我想知道是否有更好的方法方式,如果 theParam 可以有五十个值。

我的两个想法是:

1)类似于“动态命名函数调用”?

string theParam = parameterFromSomewhereElse;
callFunction("callingFunctionFor_" + theParam);
/// where callFunction is some language defined utility?

2)创建一个字典,将值作为函数

global_dict = {
"apple": callingFunctionFor_apple(),
"banana": callingFunctionFor_banana(),
"cat": callingFunctionFor_cat()
}

然后,简单地说,

global_dict[theParam](); // or something similar, ignore the syntax

查看了这些问题:

两者中的注释都表明对普通 switch-case 的偏好,例如:

string theParam = parameterFromSomewhereElse;
switch theParam:
case "apple":
callingFunctionFor_apple();
break;
case "banana":
callingFunctionFor_banana();
break;
case "cat":
callingFunctionFor_cat();
break;

但是,在我看来,它只是在视觉上比 if-else 干净一点点(如果不一样,因为 break )我原以为一个全局字典(存储所有函数引用的地方)将是一个首选解决方案,但我感觉这个故事还有更多内容。

你有什么建议?

最佳答案

下面的代码可以为您提供一些帮助,它是纯粹用 C# 编写的

 public class InstanceCreator
{
/// <summary>
/// Get the Instance from a fully qualified Name
/// </summary>
/// <param name="strFullyQualifiedName"></param>
/// <returns></returns>
public object GetInstance(string strFullyQualifiedName)
{
Type t = Type.GetType(strFullyQualifiedName);
return Activator.CreateInstance(t);
}

/// <summary>
/// Invoking the Method By Passing the Instance as well as the Method Name
/// </summary>
/// <param name="Instance">Instance Object</param>
/// <param name="MethodName">Method Name</param>
/// <returns></returns>
public object InvokeMethod(object Instance, String MethodName) {
Type t = Instance.GetType();
MethodInfo method = t.GetMethod(MethodName);
return method.Invoke(Instance, null);
}

}

public class SampleClass {

public bool doAction() {
return true;
}

}

public class TestClass {

public Dictionary<String, String> FunctionList = new Dictionary<string, string>();

public TestClass() {

this.Verify();
}

public void Verify() {
String fullyQualifiedName = typeof(SampleClass).AssemblyQualifiedName;
FunctionList.Add("SAMPLE", $"{fullyQualifiedName}#doAction");
InstanceCreator Creator = new InstanceCreator();
String[] FunctionMapping = FunctionList["SAMPLE"].Split('#');
object Test = Creator.GetInstance(FunctionMapping[0]);
bool Result = (bool)Creator.InvokeMethod(Test, FunctionMapping[1]);
}

}

关于java - 函数分类方法 : Switch-case, 或字典哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57002882/

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