在名称上具有不同数字的对象变量之间循环

本文关键字:数字 对象 变量 循环 之间 | 更新日期: 2023-09-27 18:25:10

我有以下类:

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

我想改变所有这些成员的价值观。所以我可以这样做:

Employees.field1 = "ghgf";
Employees.field2 = "ghgf";
Employees.field3 = "ghgf";
Employees.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";

我有一个问题,因为字段是在for循环中定义的var。

在名称上具有不同数字的对象变量之间循环

您可以使用反射以困难的(也是不正确的,IMO)方式进行操作。但是,如果您有30个这样的变量,请更改您的方法:使用List<string>Dictionary <whateverKey, string>来存储所有字段

如果你真的必须使用反射,你可以这样做:

var employees = new Employees();
var type = employees.GetType();
for (int i = 1; i <= 4; ++i)
    type.GetProperty("field"+i).SetValue(employees, "abcde");
Console.WriteLine(employees.field1); // Prints "abcde"

正如其他人所指出的,以这种方式使用反射似乎有点可疑。看起来您应该以不同的方式进行操作,例如使用Dictionary<string,string>

你可以这样使用反射:

        var myEmployees = new Employees();
        var properties = myEmployees.GetType().GetProperties();
        foreach (var field in properties)
        {
            field.SetValue(myEmployees, "NewValue");
        }
        // Print all field's values
        foreach (var item in properties)
        {
            Console.WriteLine(item.GetValue(myEmployees));
        }

否则,您可以使用列表或字典,或者创建一个新的结构,为您提供更大的灵活性,并使您能够控制字段的更多属性:

    struct FieldProperties
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public string Type { get; set; }
        ...
    }

    List<FieldProperties> lst = new List<FieldProperties>();

您可以尝试使用反射

Type type = typeof(Employees);
PropertyInfo pi =  this.GetType().GetProperty();
pi.SetField(this, value);

以下是MSDN链接:https://msdn.microsoft.com/en-us/library/ms173183.aspx

尝试这种方法(使用GetMembers())获取类的所有成员并循环它们。

Employees myEmployees = new Employees();
MemberInfo[] members = myType.GetMembers();
for (int i =0 ; i < members.Length ; i++)
{
    // Display name and type of the concerned member.
    Console.WriteLine( "'{0}' is a {1}", members[i].Name, members[i].MemberType);
}