本文介绍了使用反射在结构中获取结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后,在我的程序中:

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

有人知道我的错误在哪里吗?我认为结构可以通过 GetField() 访问,但也许它们不是?

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

推荐答案

typeof(Struct2).GetType() 给你一个 System.RuntimeType,而不是你的结构.删除 GetType() 以使其正常工作.

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

这篇关于使用反射在结构中获取结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:56