使用foreach循环-无法读取变量 [英] Using a foreach loop -- variable cannot be read

查看:95
本文介绍了使用foreach循环-无法读取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Should be rather simple but it's not.

这是我的代码:

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 ...
}

相当简单吧?事情是它抱怨:

Rather simple huh? The thing is it complains that :

variable 's' cannot be read at compile time. 

有什么想法吗?

推荐答案

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

To create a compile-time loop, you need to iterate over a tuple. Try this:

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

这篇关于使用foreach循环-无法读取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆