16

J'ai essayé le code suivant en utilisant le framework 2.0 et je récupère un attribut, mais quand j'essaye ceci sur le framework compact, il renvoie toujours un tableau vide. La documentation MSDN dit qu'elle est supportée, est-ce que je fais quelque chose de mal?Comment puis-je GetCustomAttributes?

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

Répondre

16

EDIT 2

Je suis vérifier avec l'équipe des FC maintenant, mais je crois que vous avez trouvé un bug. Cela montre encore mieux:

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

Dans le cadre complet je reviens ceci:

Attributes: 1 
Attributes: 1 
Attributes: 1 

Sous CF 3.5 Je reçois ceci:

Attributes: 0 
Attributes: 1 
Attributes: 1 

Alors vous pouvez le voir est tout à fait capable de renvoyer un attribut, personnalisé ou dans la BCL, mais pas le MarshalAsAttribute.


EDIT 3 D'accord, je l'ai fait un peu plus creuser, et il se trouve que le comportement des FC est en fait correct if you go by the spec. Cela va à l'encontre de toute logique, mais c'est juste.

+0

J'ai affaire à FieldInfo pour mon exemple ci-dessus. Je peux essayer et voir si PropertyInfo fonctionnerait, mais je me demande pourquoi mon exemple ne fonctionne pas. – SwDevMan81

+0

boo pour les bugs: P Savez-vous s'il y a du travail? – SwDevMan81

+0

Je suppose que le travail autour pourrait juste être de créer mon propre attribut personnalisé (juste réinventer la roue je suppose)? Depuis ressemble à ça fonctionne bien. – SwDevMan81

Questions connexes