AttributeCollection Classe

Definição

Representa um conjunto de atributos.

public ref class AttributeCollection : System::Collections::ICollection
[System.Runtime.InteropServices.ComVisible(true)]
public class AttributeCollection : System.Collections.ICollection
public class AttributeCollection : System.Collections.ICollection
[<System.Runtime.InteropServices.ComVisible(true)>]
type AttributeCollection = class
    interface ICollection
    interface IEnumerable
type AttributeCollection = class
    interface ICollection
    interface IEnumerable
Public Class AttributeCollection
Implements ICollection
Herança
AttributeCollection
Atributos
Implementações

Exemplos

O primeiro exemplo de código verifica se o BrowsableAttribute já foi definido nesta coleção. O segundo exemplo de código obtém o valor real do DescriptionAttribute para um botão. Ambos os exemplos exigem isso button1 e textBox1 foram criados num formulário. Ao usar atributos, verifique se um atributo foi definido ou aceda ao seu valor.

private:
   void ContainsAttribute()
   {
      // Creates a new collection and assigns it the attributes for button1.
      AttributeCollection^ attributes;
      attributes = TypeDescriptor::GetAttributes( button1 );
      
      // Sets an Attribute to the specific attribute.
      BrowsableAttribute^ myAttribute = BrowsableAttribute::Yes;

      if ( attributes->Contains( myAttribute ) )
      {
         textBox1->Text = "button1 has a browsable attribute.";
      }
      else
      {
         textBox1->Text = "button1 does not have a browsable attribute.";
      }
   }
void ContainsAttribute()
{
    // Creates a new collection and assigns it the attributes for button1.
    AttributeCollection attributes;
    attributes = TypeDescriptor.GetAttributes(button1);

    // Sets an Attribute to the specific attribute.
    BrowsableAttribute myAttribute = BrowsableAttribute.Yes;

    textBox1.Text = attributes.Contains(myAttribute) ? "button1 has a browsable attribute." : "button1 does not have a browsable attribute.";
}
Private Sub ContainsAttribute()
    ' Creates a new collection and assigns it the attributes for button1.
    Dim attributes As AttributeCollection
    attributes = TypeDescriptor.GetAttributes(button1)
    
    ' Sets an Attribute to the specific attribute.
    Dim myAttribute As BrowsableAttribute = BrowsableAttribute.Yes
    
    If attributes.Contains(myAttribute) Then
        textBox1.Text = "button1 has a browsable attribute."
    Else
        textBox1.Text = "button1 does not have a browsable attribute."
    End If
End Sub
private:
   void GetAttributeValue()
   {
      // Creates a new collection and assigns it the attributes for button1.
      AttributeCollection^ attributes;
      attributes = TypeDescriptor::GetAttributes( button1 );
      
      // Gets the designer attribute from the collection.
      DesignerAttribute^ myDesigner;
      myDesigner = (DesignerAttribute^)(attributes[DesignerAttribute::typeid]);
      
      // Prints the value of the attribute in a text box.
      textBox1->Text = myDesigner->DesignerTypeName;
   }
void GetAttributeValue()
{
    // Creates a new collection and assigns it the attributes for button1.
    AttributeCollection attributes;
    attributes = TypeDescriptor.GetAttributes(button1);

    // Gets the designer attribute from the collection.
    DesignerAttribute myDesigner;
    myDesigner = (DesignerAttribute)attributes[typeof(DesignerAttribute)];

    // Prints the value of the attribute in a text box.
    textBox1.Text = myDesigner.DesignerTypeName;
}
Private Sub GetAttributeValue()
    ' Creates a new collection and assigns it the attributes for button1.
    Dim attributes As AttributeCollection
    attributes = TypeDescriptor.GetAttributes(button1)
    
    ' Gets the designer attribute from the collection.
    Dim myDesigner As DesignerAttribute
    myDesigner = CType(attributes(GetType(DesignerAttribute)), DesignerAttribute)
    
    ' Prints the value of the attribute in a text box.
    textBox1.Text = myDesigner.DesignerTypeName
End Sub

Observações

A AttributeCollection classe é apenas de leitura; não implementa métodos para adicionar ou remover atributos. Deve herdar desta classe para implementar estes métodos.

Use a Count propriedade para encontrar o número de atributos que existem na coleção.

Também pode usar os métodos desta classe para consultar a coleção sobre o seu conteúdo. Chame o Contains método para verificar se existe um atributo ou array de atributos especificado na coleção. Chame o Matches método para verificar se existe um atributo especificado ou array de atributos na coleção, e que os valores dos atributos especificados são os mesmos que os valores da coleção.

Embora a maioria dos atributos tenha valores por defeito, os valores por defeito não são obrigatórios. Se um atributo não tiver valor por defeito, null é devolvido da propriedade indexada que assume um tipo. Ao definir os seus próprios atributos, pode declarar um valor padrão fornecendo um construtor que não aceita argumentos, ou definindo um campo público estático do seu tipo de atributo chamado "Default".

Construtores

Name Description
AttributeCollection()

Inicializa uma nova instância da AttributeCollection classe.

AttributeCollection(Attribute[])

Inicializa uma nova instância da AttributeCollection classe.

Campos

Name Description
Empty

Especifica uma coleção vazia que podes usar, em vez de criar uma nova. Este campo é só de leitura.

Propriedades

Name Description
Attributes

Recebe a coleção de atributos.

Count

Obtém o número de atributos.

Item[Int32]

Obtém o atributo com o número de índice especificado.

Item[Type]

Obtém o atributo com o tipo especificado.

Métodos

Name Description
Contains(Attribute)

Determina se esta coleção de atributos possui o atributo especificado.

Contains(Attribute[])

Determina se esta coleção de atributos contém todos os atributos especificados no array de atributos.

CopyTo(Array, Int32)

Copia a coleção para um array, começando no índice especificado.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
FromExisting(AttributeCollection, Attribute[])

Cria um novo AttributeCollection a partir de um .AttributeCollection

GetDefaultAttribute(Type)

Devolve o padrão Attribute de um dado Type.

GetEnumerator()

Recebe um enumerador para esta coleção.

GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
Matches(Attribute)

Determina se um atributo especificado é igual a um atributo na coleção.

Matches(Attribute[])

Determina se os atributos no array especificado são os mesmos que os atributos da coleção.

MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Implementações de Interface Explícita

Name Description
ICollection.Count

Obtém o número de elementos contidos na coleção.

ICollection.IsSynchronized

Recebe um valor que indica se o acesso à coleção é sincronizado (thread-safe).

ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso à coleção.

IEnumerable.GetEnumerator()

Retorna e IEnumerator para o IDictionary.

Métodos da Extensão

Name Description
AsParallel(IEnumerable)

Permite a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable para um IQueryable.

Cast<TResult>(IEnumerable)

Conjura os elementos de an IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base num tipo especificado.

Aplica-se a

Ver também