18

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;
  }
4

1 に答える 1

19

編集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

したがって、MarshalAsAttribute ではなく、カスタムまたは BCL 内の属性を完全に返すことができることがわかります。


編集 3 よし、もう少し掘り下げてみたところ、仕様に従えば、CF の動作は実際には正しいことがわかりました。それはすべての論理に反しますが、正しいです。

于 2009-08-12T21:47:18.010 に答える