16

我已經嘗試了使用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; 
    } 

回答

16

EDIT 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。它違背了所有的邏輯,但它是正確的。

+0

我正在處理我的上例中的FieldInfo。我可以嘗試看看PropertyInfo是否可以工作,但我想知道爲什麼我的示例不起作用。 – SwDevMan81 2009-08-12 21:52:46

+0

buo爲錯誤:P你知道是否有工作? – SwDevMan81 2009-08-14 11:56:06

+0

我想工作可能只是創建我自己的自定義屬性(只是重新發明輪子,我猜)?由於看起來像那樣工作正常。 – SwDevMan81 2009-08-14 13:08:01