我如何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; } 

编辑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好吧,我做了一点挖掘,事实certificate, 如果你遵守规范 ,CF行为实际上是正确的 。 它违背了所有逻辑,但它是正确的。