Pergunta

Eu tentei o seguinte código utilizando o framework 2.0 e recebo uma volta atributo, mas quando eu tento isso sobre o quadro compacto, ele sempre retorna uma matriz vazia. O documenation MSDN diz que seu suportado, estou fazendo algo errado?

  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;
  }
Foi útil?

Solução

EDIT 2

Então, eu estou verificando com a equipa CF agora, mas eu acredito que você encontrou um bug. Isto mostra-lo ainda melhor:

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

De acordo com o quadro completo eu voltar este:

Attributes: 1
Attributes: 1
Attributes: 1

Sob CF 3,5 fico com esta:

Attributes: 0
Attributes: 1
Attributes: 1

Assim você pode ver que é plenamente capaz de retornar um atributo, seja personalizado ou dentro da BCL, não apenas o MarshalAsAttribute.


EDIT 3 Tudo bem, eu fiz um pouco mais de escavação, e verifica-se que o comportamento CF é realmente correta se você vai pela especificação . Isso vai contra toda a lógica, mas é certo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top