c# - 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# 中,所有需要代码与关于类型及其在程序集中声明的成员的数据进行交互的事情都可以使用反射来实现。
要使用包含其名称的字符串获取字段,您可以使用方法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);
推荐阅读
- javascript - GrapesJS - 将 HTML 作为表单的一部分发布
- c# - Xamarin.forms 自定义按钮控件
- sql - 从 nvarchar 中删除第一个新行和第一个字符。女士 SQL
- javascript -
使用 JS 在可见换行符上拆分文本 [不带 \n 或] - ios - 在视图控制器中自动调整文本大小
- html - 表单验证使用 oninvalid setCustomValidity 按钮在服务器上运行
- java - 是否每个“新”都会导致至少一个 Classloader.loadClass 调用
- powershell - PowerShell 哈希表更新适用于所有条目
- c# - 如何为从枚举生成的表创建外键?
- android - 导航栏下方的底部导航栏