我正在尝试使用反射在结构中获取一个结构(我正在使用结构来封送一些继承的C DLL结构):
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()访问,但也许不是吗?
typeof(Struct2).GetType()
给你一个System.RuntimeType
,而不是你的结构。删除GetType()
以使其正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句