C# 如何通过调用字符串c中的变量名来设置值#
现在我是c#development的新手 我有来自数组的100个数据,还有100个变量 如何将100个数据与100个变量进行匹配 比如说C# 如何通过调用字符串c中的变量名来设置值#,c#,arrays,crystal-reports,C#,Arrays,Crystal Reports,现在我是c#development的新手 我有来自数组的100个数据,还有100个变量 如何将100个数据与100个变量进行匹配 比如说 for(int count = 0 ; count < array.lenght ; count++) { Var+count = array[count]; } 像这样的。因此,我尝试使用dictionary,但我认为它不起作用。下面是一个示例,说明如何使用System.Collections.Generic.dictionary动态执行您的
for(int count = 0 ; count < array.lenght ; count++)
{
Var+count = array[count];
}
像这样的。因此,我尝试使用dictionary,但我认为它不起作用。下面是一个示例,说明如何使用System.Collections.Generic.dictionary动态执行您的要求,字典中的所有键都必须是唯一的,但由于您在循环中的每个键都附加了1,这就足够了:
Dictionary<string, int> myKeyValues = new Dictionary<string, int>();
for(int count = 0 ; count < array.length; count++)
{
//Check to make sure our dictionary does not have key and if it doesn't add key
if(!myKeyValues.ContainsKey("someKeyName" + count.ToString())
{
myKeyValues.Add("someKeyName" + count.ToString(), count);
}
else
{
//If we already have this key, overwrite, shouldn't happen as you are appending a new int value to key each iteration
myKeyValues["someKeyName" + count.ToString()] = count;
}
}
Dictionary myKeyValues=newdictionary();
for(int count=0;count
您有一个数组,那么为什么要使用100个单独的变量?使用其索引访问值,就像您正在进行赋值一样(array[count]
)如果你需要一个特定的键来检索一个特定的值,你应该考虑将你的数组转换成一个字典。老实说,我不太确定你的用例是什么。C不允许你在运行时随意创建和引用没有预先确定名称的变量。这就是为什么数组/列表/字典/等等存在的原因。可能的重复这几乎可以肯定是一个X/Y问题。你在这里到底想做什么?代码是“你目前如何尝试去做”,这是不完全相同的事情(特别是对于X/Y)
Dictionary<string, int> myKeyValues = new Dictionary<string, int>();
for(int count = 0 ; count < array.length; count++)
{
//Check to make sure our dictionary does not have key and if it doesn't add key
if(!myKeyValues.ContainsKey("someKeyName" + count.ToString())
{
myKeyValues.Add("someKeyName" + count.ToString(), count);
}
else
{
//If we already have this key, overwrite, shouldn't happen as you are appending a new int value to key each iteration
myKeyValues["someKeyName" + count.ToString()] = count;
}
}