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

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

问题描述

我有以下课程:

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";

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

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";
}

但在这一行:

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

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

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

推荐答案

您可以使用反射(而不是IMO,正确的方法)来完成此操作. 但是,如果您有30个这样的变量,请更改方法:使用List<string>Dictionary <whateverKey, string>存储所有字段

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天全站免登陆