我正在使用反射来做到这一点:


        method_name := CommandMap[command]

    thing := reflect.ValueOf(self).MethodByName(method_name)

    thing_s := fmt.Sprintf("%s", thing)

    if thing_s == "<invalid reflect.Value>" {

        self.writeMessage(550, "not allowed")

    } else {

        thing.Call([]reflect.Value{})

    }

但必须有更好的方法。上面代码的重点是摆脱:


if command == "this" {

  runThis()

} else if command == "that" {

  runThat()

} etc. etc.

我不想有一棵大的 if else 树。这是一个 ftp 服务器http://github.com/andrewarrow/paradise_ftp,我需要处理 15 个左右的命令,如“USER”、“PASS”和“QUIT”等。我希望每个人都调用一个方法,例如“handleUser”或“handlePass”。但是使用反射是一个坏主意。太慢了。