16

He intentado el siguiente código usando el marco 2.0 y recupero un atributo, pero cuando pruebo esto en el marco compacto, siempre devuelve un conjunto vacío. La documentación de MSDN dice que es compatible, ¿estoy haciendo algo mal?¿Cómo puedo obtener atributos personalizados?

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

Respuesta

16

EDIT 2

Así que estoy comprobando con el equipo CF ahora, pero creo que usted ha encontrado un error. Esto demuestra aún mejor:

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

En el marco completo le regreso la siguiente:

Attributes: 1 
Attributes: 1 
Attributes: 1 

Bajo CF 3.5 me sale esto:

Attributes: 0 
Attributes: 1 
Attributes: 1 

Así que usted puede ver que es plenamente capaz de devolver un atributo, ya sea personalizado o dentro del BCL, simplemente no es MarshalAsAttribute.


EDITAR 3 bien, lo hizo un poco más de excavación, y resulta que el comportamiento CF es en realidad correct if you go by the spec. Va contra toda lógica, pero está bien.

+0

Estoy tratando con FieldInfo para mi ejemplo anterior. Puedo probar y ver si PropertyInfo funcionaría, pero me pregunto por qué mi ejemplo no funciona. – SwDevMan81

+0

abucheo para los insectos: P ¿Sabes si hay una solución alternativa? – SwDevMan81

+0

Supongo que el trabajo podría ser simplemente para crear mi propio atributo personalizado (solo reinventar la rueda, supongo) Dado que parece que funciona bien. – SwDevMan81

Cuestiones relacionadas