首页 > 解决方案 > asp.net c#我需要从存储在另一个字符串中的变量名访问变量的值

问题描述

请注意:- 我已经回答了几个链接,但它们仅导致控件。我可以轻松地使用对象来访问对象,这没有问题。问题在于在运行时访问变量。一个是指向变量,但我发现它非常艰难和僵化。所以想知道任何简单易行的方法。

我有以下要求:-

场景例如: -

 1. TextBox_mobile is a control object in aspx page
 2. mobile is a variable stored in c# .cs file
 3. I have a 135+ such controls in aspx page and want to store them in variables in .cs file on say submit button.
 4. I have stored in a table having two fields control_objects and against it variable names
 5. So when submitt is fired (click event) I want to run the assigning task with running a process to retriew control names and
variables names and assinging the values of control objects to appropriate variables.

例如,为了更实用:-

// create a variable to store textbox control
string mobile = "" 
// Text_mobile is a TextBox in aspx page
// A temporary variable to store variable in loop from table 
string var_mobile = "mobile"; // Currently I am hard coding
// now I wish to use this var_mobile to make automatically assign the value into main variable
<<var_mobile>> = TextBox_mobile.Text.Trim();
//and backend it should be actually storing same in earlier mobile variabl
mobile = TextBox_mobile.Text.Trim();

由于我有很多对象和变量,后来要处理变量,我希望一次像逻辑一样在循环中执行此操作,而不是单独分配它们。

Asp.net C# 中是否有这样的可能?

标签: c#asp.net

解决方案


在 c# 中,所有需要代码与关于类型及其在程序集中声明的成员的数据进行交互的事情都可以使用反射来实现。

要使用包含其名称的字符串获取字段,您可以使用方法GetField,然后调用返回SetValue的.FieldInfoGetField

例如,如果你有MyClass这样声明的类

class MyClass
{
    public int myField = 0;
}

您可以使用以下代码设置值myField

MyClass myClass = new MyClass();
string fieldName = "myField";
int valueToSet = 10;

typeof(MyClass).GetField(fieldName).SetValue(myClass, valueToSet);

推荐阅读