C#使用反射获取不安全结构中的固定字段类型我正在尝试使用一些固定字段获取不安全结构中的字段类型。固定字段FieldType不返回实际类型。[StructLayout(LayoutKind.Sequential,Pack=1)]publicunsafestructMyStruct{publicUInt32Field1;公共固定sbyteField2[10];公共UInt64Field3;}voidTest(){vartheStruct=newMyStruct();"";foreach(FieldInfofiintheStruct.GetType().GetFields(BindingFlags.Public|BindingFlags.Instance)){output+=fi.Name+":"+fi.FieldType.ToString()+"rn";输出:Field1:System.UInt32Field2:TestProjectNS.MyStruct+e__FixedBuffer0Field3:System.UInt64我正在寻找Field2告诉我它是sbyte而不是TestProjectNS.MyStruct+e__FixedBuffer0可以通过检索固定大小缓冲区的基础类型FixedBufferAttribute,FixedBufferAttribute适用于固定大小的缓冲区语句。foreach(FieldInfofiintypeof(MyStruct).GetFields(BindingFlags.Public|BindingFlags.Instance)){varattr=fi.GetCustomAttributes(typeof(FixedBufferAttribute),false);if(attr.Length>0)输出+=fi。名称+":"+((FixedBufferAttribute)attr[0]).ElementType+"rn";elseoutput+=fi.Name+":"+fi.FieldType+"rn";}或单个字段短版本:vartype=typeof(MyStruct).GetField("Field2").GetCustomAttributes(typeof(FixedBufferAttribute),false).Cast().Single().ElementType;作为CodeInChaos,我也需要反映这一点,但我确实有FixedBufferAttribute:[StructLayout(LayoutKind.Sequential,Pack=1)]publicstructMyStruct{publicuintField1;[FixedBuffer(typeof(sbyte),10)]publice__FixedBuffer0Field2;公共ulongField3;//嵌套类型[StructLayout(LayoutKind.Sequential,Size=10),CompilerGenerated,UnsafeValueType]publicstructe__FixedBuffer0{publicsbyteFixedElementField;很棒的问题!TestProjectNS.MyStruct+e__FixedBuffer0是嵌套类型。它包含您想要的基础类型的单个字段。因此,给定一个固定大小数组的FieldInfo,您可以:C#编译器生成类似于以下内容的内容:[StructLayout(LayoutKind.Sequential,Pack=1)]publicunsafestructMyStruct{[StructLayout(LayoutKind.Sequential,Pack=1,Size=10)]publicstructField2e__FixedBuffer0{publicsbyteFixedElementField;}publicUInt32Field1;公共Field2e__FixedBuffer0Field2;公共UInt64Field3;}除了生成的结构体的名称包含一些特殊字符,字段和嵌套类型被标记为安全关键字。CodeInChaos是对的。另一种实现方式:以上是C#学习教程:C#使用反射获取unsafe结构中固定字段类型共享的所有内容。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注—foreach(FieldInfofiintheStruct.GetType().GetFields(BindingFlags.Public|BindingFlags.Instance)){if(fi.FieldType.IsNested){输出+=fi.Name+":"+fi.FieldType。GetFields()[0].FieldType.ToString()+"rn";}else{output+=fi.Name+":"+fi.FieldType.ToString()+"rn";}}本文来自网络收藏,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
