Get struct within struct using reflection

2019-07-24 00:12发布

问题:

I'm trying to get a struct within a struct using reflection (I'm using structs to Marshal some inherited C DLL structures):

public struct Struct1
{
    public Int32 Value;
}
public struct Struct2
{
    // I0/I1 are substructures in an "Unrolled" array.
    public Struct1 I0;
    public Struct1 I1;
}

Then, in my program:

class Program
{
    static void Main(string[] args)
    {
        Struct2 MyStr = new Struct2();
        MyStr.I0.Value = 0; 
        MyStr.I1.Value = 1; 
        // I want to access I0/I1 using reflection. 
        for (int i =0; i<2;i++) { 
            string structname = "I"+i;               
            FieldInfo FI = typeof(Struct2).GetType().GetField(structname, BindingFlags.Public | BindingFlags.Instance);
            object StructureWeWant = FI.GetValue(MyStr);  // Tool errors here, saying FI is empty. 
            FieldInfo ValueFieldInsideStruct1 = typeof(Struct1).GetField("Value");
            Int32 ValueIWantToPrint = (Int32) ValueFieldInsideStruct1.GetValue(StructureWeWant);
            Console.WriteLine(structname + "  " + ValueIWantToPrint);
        }
    }
}

Anyone know where my error is? I would think structs would be accessible by GetField() but maybe they're not?

回答1:

typeof(Struct2).GetType() gives you a System.RuntimeType, not your struct. Remove GetType() to get it working.



回答2:

Replace this:

FieldInfo FI = typeof(Struct2).GetType().GetField(structname, BindingFlags.Public | BindingFlags.Instance);

with this:

FieldInfo FI = typeof(Struct2).GetField(structname, BindingFlags.Public | BindingFlags.Instance);