简体   繁体   English

C#:使用字符串变量进行调用并为其他名称命名

[英]C#: Using a string variable to call and give names to other stuff

So I want to use a string variable to call or declare other stuff. 所以我想使用字符串变量来调用或声明其他内容。 For example: I write down "some_random_name" in a text box and then press a button that calls a function which declares a variable or object called "some_random_name". 例如:我在文本框中写下“ some_random_name”,然后按一个按钮,该按钮调用一个函数,该函数声明一个名为“ some_random_name”的变量或对象。 Another example: I have declared a variable from type integer called "a_variable". 另一个例子:我从整数类型声明了一个名为“ a_variable”的变量。 I write down this name in a text box and then I press a button that calls a function which shows me the value of "a_variable". 我在一个文本框中写下该名称,然后按下一个按钮,该按钮调用一个向我显示“ a_variable”值的函数。 The second example can also be done this way: 第二个示例也可以通过以下方式完成:

if (the_wanted_variable == "a_variable") show_value(a_variable);

But that's a different question. 但这是一个不同的问题。

I have found a solution... but I couldn't understand it. 我找到了解决方案...但是我听不懂。 It was about Reflections. 这是关于思考。 Maybe a need an easier to understand explanation how to do it (no matter how big it is). 也许需要一个更容易理解的解释(如何做)(无论它有多大)。

Thanks! 谢谢!

Reflection is a way to examine/use the properties/methods of an object at runtime. 反射是一种在运行时检查/使用对象的属性/方法的方法。 Some explanations here: 这里有一些解释:

C#: Can someone explain the practicalities of reflection? C#:有人可以解释反思的实用性吗?

不必为用户输入的每个键/值对创建不同的变量,而是可以将所有键/值对存储在一个Dictionary中

Reflection is an option; 反思是一种选择; but if the needs of your program are very predictable you can avoid it for a potentially easier solution. 但是,如果您的程序需求非常可预测,则可以避免使用它,以寻求可能更简单的解决方案。

In the example you've given - if the user is presented with a textbox and they enter the name of a variable like 'MyTest1' and can press a button called 'Add 1' you could accomplish it with a key/value pair dictionary. 在您给出的示例中-如果为用户显示一个文本框,并且他们输入了变量“ MyTest1”之类的名称,并且可以按下名为“ Add 1”的按钮,则可以使用键/值对字典来实现。

In other words - if the user enters text that they haven't entered before, you create a new integer value and set it's value to 0. If the user clicks on a button, it calls a predefined function on that value associated with that key. 换句话说-如果用户输入以前从未输入过的文本,则会创建一个新的整数值并将其值设置为0。如果用户单击按钮,它将在与该键关联的值上调用预定义函数。 'Add 1' to a newly created key would return '1'. 将“添加1”添加到新创建的键中将返回“ 1”。

You can use a dictionary to store the variables. 您可以使用字典来存储变量。

Dictionary<string,string> Variables;

if you don't want strings, you can use a Dictionary<string, object> but you have to be aware of the type to cast it when you click the button. 如果您不想使用字符串,则可以使用Dictionary<string, object>但是在单击按钮时必须知道要强制转换的类型。

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

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