C# 我想在C语言中动态地获取选项#

C# 我想在C语言中动态地获取选项#,c#,forms,dynamic,for-loop,options,C#,Forms,Dynamic,For Loop,Options,当我提交表单时,我想使用for循环获取选项值,我有这段代码,如何才能成功地使该模块工作 for (int j = 0; j < i; j++) { String gender = Request.Form['"Option"+i'].ToString(); Response.Write(gender); } for(int j=0;j

当我提交表单时,我想使用for循环获取选项值,我有这段代码,如何才能成功地使该模块工作

        for (int j = 0; j < i; j++)
        {
            String gender = Request.Form['"Option"+i'].ToString();
            Response.Write(gender);
        }
for(int j=0;j
我想你只需要:

String gender = Request.Form["Option" + i].ToString();
事实上,这是一个索引器参数在这里是无关的。就是这样,

int x = 5;
String y = "Option" + x; // Now y is "Option5"
for (int j = 0; j < totalFields; j++)
{
    string key = string.Format("Option{0}", j);
    string gender = Request.Form[key].ToString();
    Response.Write(gender);
}
但是,看看您的循环,您可能实际上想要使用
j
而不是
i

for (int j = 0; j < i; j++)
for(int j=0;j
i
的值在循环过程中不会改变。

试试这个

String gender = Request.Form["Option" + j].ToString();
你可以这样做

for (int j = 0; j < i; j++)
{
    string key = string.Format("Option{0}", i);
    string gender = Request.Form[key].ToString();
    Response.Write(gender);
}

当简单的连接可以工作时,为什么还要麻烦使用
string.Format
?@JonSkeet当然你也可以使用连接。我不喜欢使用连接。如果必须的话,您可以在以后更容易地抽象出
键的格式
——无论格式是
选项{0}
还是
{0}选项
选项{0}新建
,调用都是相同的。使用串联,您必须修改字符串的串联方式。@p.s.w.g:这听起来像是过早的泛化。以后真的不难改变,这将是一个完全本地化的改变。@JonSkeet我同意这是没有必要的。这就是我回答这个问题的方式。如果我在另一天看到这个问题(当时我还没有完成重写使用字符串串联的有缺陷代码),我可能会给出不同的答案:)