C# 使用反射在struct中获取struct

C# 使用反射在struct中获取struct,c#,reflection,struct,C#,Reflection,Struct,我正在尝试使用反射获取结构中的结构(我正在使用结构封送一些继承的C DLL结构): 然后,在我的程序中: 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 re

我正在尝试使用反射获取结构中的结构(我正在使用结构封送一些继承的C DLL结构):

然后,在我的程序中:

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);
        }
    }
}
类程序
{
静态void Main(字符串[]参数)
{
struct2mystr=newstruct2();
MyStr.I0.Value=0;
MyStr.I1.Value=1;
//我想使用反射访问I0/I1。
对于(int i=0;i替换为:

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

FieldInfo FI = typeof(Struct2).GetField(structname, BindingFlags.Public | BindingFlags.Instance);
替换此项:

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

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

typeof(Struct2).GetType()
给你一个
系统。RuntimeType
,而不是你的结构。删除
GetType()
,让它工作。

typeof(Struct2).GetType()
给你一个
系统。RuntimeType
,而不是你的结构。删除
GetType()
让它工作。

IMO除非处理vb/c DLL,否则struct没有用处。如果使用类反射,效果很好。IMO除非处理vb/c DLL,否则struct没有用处。如果使用类反射,效果很好。