猿问

使用反射在类中循环遍历结构

public struct volt_struct

{

    public string volt1;

    public string volt2;

    public string volt2;

    public string volt3;

}

private class Injection_class

{

    public volt_struct stru1;

    public volt_struct stru2;

    public volt_struct stru3;

    public volt_struct stru4;

    public volt_struct stru5;

    public volt_struct stru6;

}


public void main()

{

    Injection_class Time = new Injection_class();


    //Here is code that fills Time with Time values as string type


    string s="";

    FieldInfo[] fi_inner = Time.stru1.GetType().GetFields();

    FieldInfo[] fi_outer = Time.GetType().GetFields();


    // This part is wrong, but shows what I want to achive.

    foreach(FieldInfo field_outer in fi_outer)

    {

        foreach(FieldInfo field_inner in fi_inner)

        {

            s = string.concat(s+field_outer.field_inner.GetValue(Time) + ";");

        }

    }


}

我想使用反射将存储在 Time 中的字符串连接到字符串 s 中。稍后我必须修改类和结构,我不想调整连接代码。


通过对类中的每个结构使用 foreach 循环,我得到了想要的结果。


 foreach (FieldInfo field in fi_inner)

{

    s = string.Concat(s + field.GetValue(Time.stru1) + ";");

    //field.SetValue(Time, "not measured"); //reset value

}

foreach (FieldInfo field in fi_inner)

{

    s = string.Concat(s + field.GetValue(Time.stru2) + ";");

    //field.SetValue(Time, "not measured"); //reset value

}

//and so one for each other struct

我想像我给出的第一个例子一样实现它。这可能吗?


哆啦的时光机
浏览 189回答 2
2回答

大话西游666

对“field_inner”进行操作的 FieldInfo 属性需要引用“volt_struct”类型的对象,因此 Time 在这里不起作用。您需要先在“field_outer”上执行 GetValue,如下所示:foreach(FieldInfo field_outer in fi_outer){    var outer_object = field_outer.GetValue(Time);    if (outer_object == null) throw someexception;    foreach (FieldInfo field_inner in fi_inner)    {        s = string.concat(s+field_inner.GetValue(outer_object) + ";");    }}如果您想改变父类型和子类型,您可以将它们作为 System.Type 参数传入,或者您可以编写具有两个类型参数的泛型函数。您也可以将 'fi_inner =' 移入外循环并执行 fi_inner = outer_object.GetType().GetFields()。这将连接任何类型的子对象上的字符串。
随时随地看视频慕课网APP
我要回答