使用C#中的字符串数组中的项创建变量名 [英] Create variable names using items from a string array in C#

查看:148
本文介绍了使用C#中的字符串数组中的项创建变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用字符串数组来创建带有循环的多个变量.

I want to use an array of strings to create several variables with a loop.

string[] testArray = new string[5] {"Test1", "Test2", "Test3", "Test4", "Test5"};

for (int index = 0; index < testArray.length; index++)
{
    string nameArray[index];
}

这给出了两个错误:

  • 声明了变量'nameArray',但从未使用
  • 不良数组声明符:要声明托管数组,秩说明符应位于 变量的标识符.要声明固定大小的缓冲区,请使用 字段类型之前的固定关键字.
  • The variable 'nameArray' is declared but never used
  • Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.

我想我为什么我尝试的方法不起作用...还有另一种方法可以做到这一点吗?

I think I get why the way I'm trying doesn't work... is there another way to do this?

推荐答案

要直接回答您的问题,无法完成. C#不允许在运行时命名变量.但是,您可以使用字典来解决(某种程度上).例如:

To directly answer your question, it cannot be done. C# does not allow naming of variables at runtime. However, you can get around this (somewhat) by using a dictionary. For example:

string[] testArray = new string[5] {"Test1", "Test2", "Test3", "Test4", "Test5"};
var nameDict = new Dictionary<string, string>();
for (int index = 0; index < testArray.Length; index++)
{
    nameDict.Add(testArray[index], "some string value");
}

这将为您提供一个字典,您要在其中存储的值(可以是字符串,对象或任何POCO)由字符串名称(例如"Test1","Test2","Test3")键入.

This will give you a dictionary, where the value you want to store (could be string, object, or any POCO) is keyed by a string name eg "Test1", "Test2", "Test3".

这通常是不好的做法,也是一个坏主意.它使调试变得非常困难,并且被认为是非常糟糕的做法.我建议您在可能的情况下找到其他处理方式.

这篇关于使用C#中的字符串数组中的项创建变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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