循环遍历名称上具有不同编号的对象变量 [英] Loop through object variables with different number on the name

查看:24
本文介绍了循环遍历名称上具有不同编号的对象变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

公共类员工{公共字符串字段 1 { 获取;放;}公共字符串 field2 { 获取;放;}公共字符串 field3 { 获取;放;}公共字符串 field4 { 获取;放;}}

而且我想更改所有这些成员的值.所以我可以做这样的事情:

Employees.field1 = "ghgf";员工.field2 = "ghgf";员工.field3 = "ghgf";员工.field4 = "ghgf";

但它非常丑陋.并且会员数量将是30,所以这不是一个好方法......我想使用 for 循环,遍历所有成员并动态获取相关字段并更改值.例如:

for(int i=1; i<4; i++) {var field = "field" + i;Employees.field(the Var!!) = "fgdfd";}

但在这一行:

Employees.field(the Var!!) = "fgdfd";

我有一个问题,因为 field 是在 for 循环中定义的 var.

解决方案

您可以使用反射以困难的(而不是正确的,IMO)方式来完成.但是,如果您有 30 个这样的变量,请更改您的方法:使用 ListDictionary 来存储所有字段>

I have the following class:

public class Employees {
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
public string field4 { get; set; }
}

And i want to change values to all those members. so i can to something like that:

Employees.field1 = "ghgf";
Employees.field2 = "ghgf";
Employees.field3 = "ghgf";
Employees.field4 = "ghgf";

but it's very ugly. and the amount of members will be 30, so this is not a good way... I want to use for loop, that run over all the members and dynamic took the relevant field and change the value. for example:

for(int i=1; i<4; i++) {
var field = "field" + i;
Employees.field(the Var!!) = "fgdfd";
}

but in this line:

Employees.field(the Var!!) = "fgdfd";

I have a problem because field is the var that was defined in the for loop.

解决方案

You can do it the hard (and not correct, IMO) way, using reflection. But if you have 30 variable like this, change your approach: use a List<string>, or a Dictionary <whateverKey, string> to store all your fields

这篇关于循环遍历名称上具有不同编号的对象变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆