asp.net c# 我需要从存储在另一个字符串中的变量名中访问变量的值。

问题描述 投票:-1回答:1

请注意:-我已经回答了几个链接,但它们只指向控件。我可以很容易地使用对象来访问对象,没有问题。问题是在运行时访问变量。一个是直接访问变量,但我发现它非常困难和僵化。所以想知道有什么简单易行的方法。

我有一个需求如下:-

如:-的场景:-。

 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.

为了让e.g.更加实用:-。

// 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
1个回答
1
投票

在c#中,这个和所有需要代码与类型及其成员在汇编中声明的数据进行交互的事情,都可以通过使用 反思.

要使用包含其名称的字符串获取字段,你可以使用方法 GetField 然后叫 SetValue 关于 FieldInfo 所回 GetField.

例如,如果你的类名为 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);

0
投票

按照Kacper提示的快速回答,我可以用他的点对点解决。

CommonClass.cs

public class CommonClass
{
     public string mobile = "";
     public CommonClass()
     {
         //
         // TODO: Add constructor logic here
         //
      }
}

我的代码在.cs文件中:-

    string mobile = "";

    CommonClass obj_class = new CommonClass();
    string fieldname = "mobile";
    typeof(CommonClass).GetField(fieldname).SetValue(obj_class, TextBox_mobile.Text);

    mobile = obj_class.mobile.Trim();
© www.soinside.com 2019 - 2024. All rights reserved.