代码之家  ›  专栏  ›  技术社区  ›  SwDevMan81

如何获取GetCustomAttributes?

  •  19
  • SwDevMan81  · 技术社区  · 16 年前

      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 回复  |  直到 16 年前
        1
  •  17
  •   ctacke    13 年前

    编辑2

    所以我现在正在和CF团队核实,但我相信你发现了一个bug。这更能说明问题:

    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 这违背了所有的逻辑,但这是对的。

    推荐文章