AttributeCollection Classe

Definição

Representa uma coleção de atributos.

public ref class AttributeCollection : System::Collections::ICollection
public class AttributeCollection : System.Collections.ICollection
[System.Runtime.InteropServices.ComVisible(true)]
public class AttributeCollection : System.Collections.ICollection
type AttributeCollection = class
    interface ICollection
    interface IEnumerable
[<System.Runtime.InteropServices.ComVisible(true)>]
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 conjunto foi definido nesta coleção. O segundo exemplo de código obtém o valor real de DescriptionAttribute um botão. Ambos os exemplos exigem isso button1 e textBox1 foram criados em um formulário. Ao usar atributos, verifique se um atributo foi definido ou acesse 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.";
      }
   }
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.";
 }
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;
   }
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[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

Comentários

A AttributeCollection classe é somente leitura; não implementa métodos para adicionar ou remover atributos. Você deve herdar dessa classe para implementar esses métodos.

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

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

Embora a maioria dos atributos tenha valores padrão, os valores padrão não são necessários. Se um atributo não tiver nenhum valor padrão, null será retornado da propriedade indexada que usa um tipo. Ao definir seus próprios atributos, você pode declarar um valor padrão fornecendo um construtor que não usa argumentos ou definindo um campo estático público do tipo de atributo chamado "Padrão".

Construtores

AttributeCollection()

Inicializa uma nova instância da classe AttributeCollection.

AttributeCollection(Attribute[])

Inicializa uma nova instância da classe AttributeCollection.

Campos

Empty

Especifica uma coleção vazia que você pode usar, em vez de criar uma nova. Este campo é somente leitura.

Propriedades

Attributes

Obtém 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

Contains(Attribute)

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

Contains(Attribute[])

Determina se essa coleção de atributos contém todos os atributos especificados na matriz de atributos.

CopyTo(Array, Int32)

Copia a coleção para uma matriz, 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 de um AttributeCollection existente.

GetDefaultAttribute(Type)

Retorna o Attribute padrão de um determinado Type.

GetEnumerator()

Obtém um enumerador para esta coleção.

GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
Matches(Attribute)

Determina se um atributo especificado é o mesmo que um atributo na coleção.

Matches(Attribute[])

Determina se os atributos na matriz especificada são os mesmos que os atributos na coleção.

MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

ICollection.Count

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

ICollection.IsSynchronized

Obtém 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 um IEnumerator para o IDictionary.

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

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

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.

Aplica-se a

Confira também