我如何GetCustomAttributes?

SwD*_*n81 18 c# attributes compact-framework 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;
  }
Run Code Online (Sandbox Code Playgroud)

cta*_*cke 18

编辑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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Attributes: 1
Attributes: 1
Attributes: 1
Run Code Online (Sandbox Code Playgroud)

在CF 3.5下,我得到了这个:

Attributes: 0
Attributes: 1
Attributes: 1
Run Code Online (Sandbox Code Playgroud)

因此,您可以看到它完全能够返回属性,无论是自定义还是BCL内部,而不是MarshalAsAttribute.


编辑3 好吧,我做了一点挖掘,事实证明,如果你遵守规范,CF行为实际上是正确.它违背了所有逻辑,但它是正确的.