【问题标题】:Using a foreach loop -- variable cannot be read使用 foreach 循环——无法读取变量
【发布时间】:2014-04-15 08:11:57
【问题描述】:

应该很简单,但事实并非如此。

这是我的代码:

string cases()
{
    string ret = "";
    string[] methods;

    methods = [__traits(derivedMembers,mixin("Math"))];
    foreach (string s; methods) ret ~= "case \"" ~ s ~ "\": return Math."~s~"(params);";

    methods = [__traits(derivedMembers,mixin("OtherClass"))];
    foreach (string s; methods) ret ~= "case \"" ~ s ~ "\": return OtherClass."~s~"(params);";

    return ret;
}

string execute(string what, string[] params)
{
    switch (what)
    {
        mixin(cases());
        default: break;
    }
    return "";
}

我想做的事:

const string[] arrayWithClassNames = ["Math","SomeClass"];
foreach (string s; arrayWithClassNames)
{
     methods = ...
     foreach ...
}

相当简单吧?问题是它抱怨:

variable 's' cannot be read at compile time. 

有什么想法吗?

【问题讨论】:

    标签: mixins d dmd


    【解决方案1】:

    要创建一个编译时循环,您需要遍历一个元组。试试这个:

    alias classNames = TypeTuple!("Math","SomeClass");
    foreach (string s; classNames)
    {
        ...
    }
    

    【讨论】:

    • A-M-A-Z-I-N-G!非常感谢! :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2018-03-04
    相关资源
    最近更新 更多