与反射不安全结构固定场的C#获取类型 [英] C# Get type of fixed field in unsafe struct with reflection

查看:209
本文介绍了与反射不安全结构固定场的C#获取类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让使用一些固定字段不安全结构的字段类型。固定域的FieldType不返回的实际类型。

I'm trying to get the field types of an unsafe struct using some fixed fields. The fixed fields FieldType do not return the actual type.

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

}



输出:

Output:

字段1: System.UInt32

字段2: TestProjectNS.MyStruct + LT;字段2> e__FixedBuffer0

字段3: System.UInt64形式

我在寻找字段2 来告诉我这是为sbyte 而不是 TestProjectNS.MyStruct +<字段2> e__FixedBuffer0

I'm looking for Field2 to tell me it's sbyte instead of TestProjectNS.MyStruct+<Field2>e__FixedBuffer0

推荐答案

在固定大小的缓冲区的基本类型可通过检索的 FixedBufferAttribute ,它是在固定大小的缓冲区声明应用。

The Fixed Size Buffer's underlying type can be retrieved through the FixedBufferAttribute, which is applied on the fixed size buffer statement.

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



还是单场短版:

Or the single field short version:

var type = typeof (MyStruct)
            .GetField("Field2")
            .GetCustomAttributes(typeof (FixedBufferAttribute), false)
            .Cast<FixedBufferAttribute>()
            .Single()
            .ElementType;



由于CodeInChaos,我还需要体现出这一点,但我确实有 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;
    }
}



真棒的问题!

Awesome question!

这篇关于与反射不安全结构固定场的C#获取类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆