如何通过从字符串c#调用变量名来设置值
How to set value by call variable name from string c#
现在我是 c# 开发的新手。
我有 100 个来自数组的数据,还有 100 个变量。
如何将 100 个数据与 100 个变量匹配?
例如
for(int count = 0 ; count < array.lenght ; count++)
{
Var+count = array[count];
}
像这样。
或者你们有其他解决方案请帮助我。我不想这样做
手动将 Var1 设置为 Var100。
更多信息
实际上我需要将数组值添加到 CrystalReport
中的文本对象
例如,如果我想添加值
TextObject txtLot1 = (TextObject)report.ReportDefinition.Sections["Section4"].ReportObjects["txtLot1"];
txtLot1.Text = Arrays[i]
像这样。所以,我尝试使用字典,但我认为它不会起作用。
这是一个使用 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;
}
}
现在我是 c# 开发的新手。
我有 100 个来自数组的数据,还有 100 个变量。
如何将 100 个数据与 100 个变量匹配?
例如
for(int count = 0 ; count < array.lenght ; count++)
{
Var+count = array[count];
}
像这样。
或者你们有其他解决方案请帮助我。我不想这样做
手动将 Var1 设置为 Var100。
更多信息 实际上我需要将数组值添加到 CrystalReport
中的文本对象例如,如果我想添加值
TextObject txtLot1 = (TextObject)report.ReportDefinition.Sections["Section4"].ReportObjects["txtLot1"];
txtLot1.Text = Arrays[i]
像这样。所以,我尝试使用字典,但我认为它不会起作用。
这是一个使用 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;
}
}