D:使用带有名称的字符串变量调用函数

J.R*_*len 7 d

D学习者在这里......如果我有一个字符串(仅在运行时已知的值),这是我想要调用的函数的名称,我该怎么做?以下示例......

void func001() {
//stuff
}

void func002() {
//stuff
}

// .........

void func100() {
//stuff
}

void main(char[][] args) {
  auto funcnum = to!uint(args[0]);
  auto funcname = format('func%03d', funcnum);
  ///// need to run the function named 'funcname' here
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*ppe 12

这是使用编译时反射的示例.有了__traits(allMembers),我们可以循环遍历聚合(模块,结构,类等)中所有成员的名称,并且__traits(getMember),我们可以通过名称获取成员并执行调用它之类的操作.

棘手的部分getMember需要一个编译时字符串,所以我们不能直接传递命令行参数.相反,我们构建一个switch从参数派遣 - 几乎就像你手工一样,但不是自己编写所有名称,而是让循环处理它.

这里只有两个功能,但它可以扩展到任意数量的功能而无需修改main功能.

查看内联的更多评论:

import std.stdio;

// I'm grouping all the commands in a struct
// so it is easier to loop over them without
// other stuff getting in the way
struct Commands {
    // making them all static so we don't need to instantiate it
    // to call commands. This is often not the best way but it makes
    // for an easy demo and does work well a lot of the time.
    static:

    // Also assuming they all return void and have no arguments.
    // It is possible to handle other things, but it gets a lot
    // more involved. (I think my book example goes partially into
    // it, or something like my web.d goes all the way and generates
    // web/http and javascript/json apis from a full signature but that
    // code is pretty unreadable...)

    void func001() {
        writef("func001 called\n");
    }
    void func002() {
        writef("func002 called\n");
    }
}

void main(string[] args) {
    if(args.length > 1)
    // we switch on the runtime value..
    // the label will be used below
    outer: switch(args[1]) {
        // then loop through the compile time options to build
        // the cases. foreach with a compile time argument works
        // a bit differently than runtime - it is possible to build
        // switch cases with it.
        //
        // See also: http://dlang.org/traits.html#allMembers
        // and the sample chapter of my book
        foreach(memberName; __traits(allMembers, Commands)) {
            case memberName:
                // get the member by name with reflection,
                // and call it with the parenthesis at the end
                __traits(getMember, Commands, memberName)();

            // breaking from the labeled switch so we don't fallthrough
            // and also won't break the inner loop, which we don't want.
            break outer;
        }

        default: // default is required on most D switches
            writef("No such function, %s!\n", args[1]);
            break;
    }
    else { // insufficient args given
        writeln("Argument required. Options are:");
        // we can also loop to list names at runtime
        foreach(memberName; __traits(allMembers, Commands)) {
            writeln(memberName);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Abs*_*ype 6

您还可以使用关联数组,假设每个函数都匹配相同的原型:

module test;
import std.format, std.stdio, std.conv;

void func001() {
    writeln(__FUNCTION__);
}

void func002() {
    writeln(__FUNCTION__);
}

alias Proto = void function();
Proto[string] funcs;

// assign the functions to a string in the static constructor
static this() {
    funcs["func001"] = &func001;
    funcs["func002"] = &func002;
}

void main(string[] args) {
    if (args.length < 2) return;
    //!\ note that first argument is always the application exename /!\\
    auto funcnum = to!uint(args[1]);
    auto funcname = format("func%03d", funcnum);

    // try to get the matching function pointer
    Proto* f = funcname in funcs;

    // call it if the function pointer is assigned
    if (f != null) (*f)(); 
}
Run Code Online (Sandbox Code Playgroud)

请注意,在您的初始示例中,您已使用参数发生错误.args[0]始终设置为应用程序exename.第一个自定义参数实际上是args[1].

如果将1或2作为参数传递并打印,我建议的解决方案将起作用:

test.func001

test.func002

或无


A. *_*mov 3

您不必将字符串(参数、运行时)转换为函数调用(大部分是编译的)并进入大量的内存/运行时/DLL 内容,而只需做一个简单的if声明即可。

一些伪给你的,如果你愿意的话,我很乐意将其翻译为 D -

Given functions func001, func002, func003:
 Read and store a string input
 if the input is equal to "func001":
  Call func001
 else if input is equal to "func002":
  Call func002
 else if the input is equal to "func003":
  Call func 003
 else
  Print "Not a valid function name. Available functions are func001, func002, and func003."
Run Code Online (Sandbox Code Playgroud)

  • 在 D 中,您还可以通过编译时反射自动生成该链。我的书的免费示例章节详细介绍了如何执行此操作的示例:https://www.packtpub.com/application-development/d-cookbook 但是,是的,这是简短列表的最简单方法。 (2认同)