简体   繁体   English

C# 如何通过拼接字符串获取变量值?

[英]C# How to get variable value through concated string?

i am switching from different programing language and i would like to ask if this approach is correct, or if i should use different method.我正在从不同的编程语言切换,我想问一下这种方法是否正确,或者我是否应该使用不同的方法。

Simple example: I have set of variables with values, and based on user input i want to use concated string to read value from correct variable.简单示例:我有一组带有值的变量,并且根据用户输入,我想使用连接字符串从正确的变量中读取值。

int userSelection;
int finalPointValue;

int pointID_1 = 10;
int pointID_2 = 3;
int pointID_3 = 80;
...

// read user selection
...
// obtain value of selected variable
finalPointValue = "pointID_" +userSelection;

So if user select 3 then final value would be 80, and so on (i am really trying to simplify this example).因此,如果用户 select 3 则最终值为 80,依此类推(我真的想简化此示例)。

I did not find straight answer on internet, but i get this code to do the work (bit different to the example but concept is the same):我没有在互联网上找到直接的答案,但我得到了这个代码来完成这项工作(与示例有点不同,但概念是相同的):

using System.Reflection;

public class Form1
{
  public string langID;
  public static string sText_EN = "Text in english";
  public static string sText_SK = "Text in slovak";

  // some code to obtain "EN" or "SK" in langID
  ...

  private void ChangeLanguage()
  {
    lblText.Text = Convert.ToString(typeof(Form1).GetField("sText_" +langID).GetValue(null));
  }
}

I mean, this code works for me, but it looks like this approach is not commonly used (or at least i had quite difficul time to found this solution).我的意思是,这段代码对我有用,但看起来这种方法并不常用(或者至少我很难找到这个解决方案)。

So, is there any other way how to directly read value from variable with concated string?那么,有没有其他方法可以直接从带有连接字符串的变量中读取值? Or do you use different method for this kind of situations?或者你对这种情况使用不同的方法?

Thanks in advance.提前致谢。

Since the input is an integer value you can use it to index an array.由于输入是 integer 值,您可以使用它来索引数组。 This is very fast and simple.这是非常快速和简单的。

//      index =        0           1  2   3
int[] pointId = { 0 /* unused */, 10, 3, 80 };

int finalPointValue = pointId[userSelection];

Array indices are 0-based, so I inserted a dummy value at the beginning of the array since the user inputs start at 1. If the user selection was starting at a higher number, (eg, 100, 101, 102), then you would just subtract this offset.数组索引是从 0 开始的,所以我在数组的开头插入了一个虚拟值,因为用户输入从 1 开始。如果用户选择从更高的数字开始(例如,100、101、102),那么你只会减去这个偏移量。

int[] pointId = { 10, 3, 80 };

int finalPointValue = pointId[userSelection - 100];

This works because the user inputs are in sequence with no holes.这是有效的,因为用户输入是按顺序排列的,没有漏洞。 If they were arbitrary values or strings for example, you could use a dictionary.例如,如果它们是任意值或字符串,您可以使用字典。

Example:例子:

Dictionary<string, int> pointId = new() {
    ["one"] = 10,
    ["two"] = 3,
    ["three"] = 80
};
string input = Console.ReadLine();
if (pointId.TryGetValue(input, out int id)) {
    Console.WriteLine($"The Id of point {input} is {id}");
}

A dictionary lookup is not as fast as indexing an array;字典查找不如索引数组快; however, it is an O(1) operation .但是,这是一个O(1)操作 Ie, the speed does not depend on the size of the dictionary.即,速度不取决于字典的大小。

Instead of resorting to reflection you can store your language options in a Dictionary and use the user input as the key to access the language ID's corresponding value.您可以将语言选项存储在Dictionary中,并使用用户输入作为访问语言 ID 对应值的key ,而不是诉诸反射。

var options = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    { "EN", "Text in English" },
    { "SK", "Text in Slovak" }
};

// Read the users language ID selection.
var langID = Console.ReadLine();
if (options.TryGetValue(langID, out var value))
{
    Console.WriteLine(value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM