Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c# - How do I GetCustomAttributes?

I have tried the following code using the 2.0 framework and I get an attribute back, but when I try this on the compact framework, it always returns an empty array. The MSDN documenation says its supported, am I doing something wrong?

  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;
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT 2

So I'm checking with the CF team now but I believe you've found a bug. This shows it even better:

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());
    }
}

Under the full framework I get back this:

Attributes: 1
Attributes: 1
Attributes: 1

Under CF 3.5 I get this:

Attributes: 0
Attributes: 1
Attributes: 1

So you can see it's fully capable of returning an attribute, either custom or within the BCL, just not the MarshalAsAttribute.


EDIT 3 Alright, I did a little more digging, and it turns out that the CF behavior is actually correct if you go by the spec. It goes against all logic, but it's right.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...