什么是更好的功能分类方法:切换大小写或词典?

时间:2019-07-12 08:14:46

标签: java c# android

[编辑:下面的代码示例与语言无关,尽管鼓励提供有关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乱扔垃圾。)我认为最好将全局词典(可以存储所有函数引用的位置)存储在一个全局词典中,但是我觉得这个故事还有更多的东西。

您推荐什么?

1 个答案:

答案 0 :(得分:0)

下面的代码可以为您提供帮助,它完全是用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]);
    }

}