我正在尝试使用一些固定字段来获取不安全结构的字段类型。固定字段FieldType不返回实际类型。

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct MyStruct
{
   public UInt32 Field1;
   public fixed sbyte Field2[10];
   public UInt64 Field3;
}

void Test()
{
   var theStruct = new MyStruct();
   string output = "";
   foreach (FieldInfo fi in theStruct.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
   {
      output += fi.Name + ": " + fi.FieldType.ToString() + "\r\n";
   }

}

输出:

栏位1:System.UInt32
栏位2:TestProjectNS.MyStruct+<Field2>e__FixedBuffer0
栏位3:System.UInt64
我正在寻找Field2来告诉我它是sbyte而不是TestProjectNS.MyStruct+<Field2>e__FixedBuffer0

最佳答案

固定大小缓冲区的基础类型可以通过FixedBufferAttribute检索,该类型适用于固定大小缓冲区语句。

foreach (FieldInfo fi in typeof(MyStruct).GetFields(BindingFlags.Public | BindingFlags.Instance))
{
    var attr = fi.GetCustomAttributes(typeof(FixedBufferAttribute), false);
    if(attr.Length > 0)
        output += fi.Name + ": " + ((FixedBufferAttribute)attr[0]).ElementType + "\r\n";
    else
        output += fi.Name + ": " + fi.FieldType + "\r\n";
}

或单字段简短版本:
var type = typeof (MyStruct)
            .GetField("Field2")
            .GetCustomAttributes(typeof (FixedBufferAttribute), false)
            .Cast<FixedBufferAttribute>()
            .Single()
            .ElementType;

作为CodeInChaos,我也需要反射(reflect)它,但是我确实有FixedBufferAttribute:
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct MyStruct
{
    public uint Field1;
    [FixedBuffer(typeof(sbyte), 10)]
    public <Field2>e__FixedBuffer0 Field2;
    public ulong Field3;
    // Nested Types
    [StructLayout(LayoutKind.Sequential, Size=10), CompilerGenerated, UnsafeValueType]
    public struct <Field2>e__FixedBuffer0
    {
       public sbyte FixedElementField;
    }
}

很棒的问题!

09-04 13:55
查看更多