我如何GetCustomAttributes?

时间:2009-08-12 21:41:06

标签: c# compact-framework attributes marshalling getcustomattributes

我使用2.0框架尝试了以下代码,然后我得到了一个属性,但是当我在紧凑框架上尝试这个时,它总是返回一个空数组。 MSDN文档说它支持,我做错了吗?

  Test x = new Test();
  FieldInfo field_info = x.GetType().GetField("ArrayShorts");
  object[] custom_attributes = field_info.GetCustomAttributes(typeof(MarshalAsAttribute), false);

  [StructLayout(LayoutKind.Sequential)]
  public struct Test
  {
     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
     public ushort[] ArrayShorts;
  }

1 个答案:

答案 0 :(得分:17)

编辑2

所以我现在正在与CF团队核实,但我相信你发现了一个错误。这表明它更好:

public class MyAttribute : Attribute
{
    public MyAttribute(UnmanagedType foo)
    {
    }

    public int Bar { get; set; }
}

[StructLayout(LayoutKind.Sequential)]
public struct Test
{
    [CLSCompliant(false)]
    [MyAttribute(UnmanagedType.ByValArray, Bar = 4)]
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    public ushort[] ArrayShorts;
}

class Program
{
    static void Main(string[] args)
    {

        FieldInfo field_info = typeof(Test).GetField("ArrayShorts");
        object[] custom_attributes = field_info.GetCustomAttributes(typeof(MarshalAsAttribute), false);
        Debug.WriteLine("Attributes: " + custom_attributes.Length.ToString());
        custom_attributes = field_info.GetCustomAttributes(typeof(MyAttribute), false);
        Debug.WriteLine("Attributes: " + custom_attributes.Length.ToString());
        custom_attributes = field_info.GetCustomAttributes(typeof(CLSCompliantAttribute), false);
        Debug.WriteLine("Attributes: " + custom_attributes.Length.ToString());
    }
}

在完整的框架下,我得到了回复:

Attributes: 1
Attributes: 1
Attributes: 1

在CF 3.5下我得到了这个:

Attributes: 0
Attributes: 1
Attributes: 1

所以你可以看到它完全有能力返回一个属性,无论是自定义还是BCL内部,而不是MarshalAsAttribute。


编辑3 好吧,我做了一点挖掘,结果证明CF行为实际上是correct if you go by the spec。它违背了所有逻辑,但它是正确的。