DefaultValueAttribute Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Especifica o valor padrão de uma propriedade.
public ref class DefaultValueAttribute : Attribute
public ref class DefaultValueAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.All)]
public class DefaultValueAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.All)]
public sealed class DefaultValueAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.All)>]
type DefaultValueAttribute = class
inherit Attribute
Public Class DefaultValueAttribute
Inherits Attribute
Public NotInheritable Class DefaultValueAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
O exemplo a falseseguir define o valor padrão como MyProperty .
private:
bool _myVal;
public:
[DefaultValue(false)]
property bool MyProperty
{
bool get()
{
return _myVal;
}
void set( bool value )
{
_myVal = value;
}
}
[DefaultValue(false)]
public bool MyProperty { get; set; }
Private _myVar As Boolean = False
<DefaultValue(False)>
Public Property MyProperty() As Boolean
Get
Return _myVar
End Get
Set
_myVar = Value
End Set
End Property
O exemplo a seguir verifica o valor padrão de MyProperty. Primeiro, o código obtém uma PropertyDescriptorCollection com todas as propriedades do objeto. Em seguida, ele indexa para obter PropertyDescriptorCollectionMyProperty. Em seguida, retorna os atributos dessa propriedade e os salva na variável de atributos.
Em seguida, o exemplo imprime o valor padrão recuperando-o DefaultValueAttributeAttributeCollectione gravando seu nome na tela do console.
// Gets the attributes for the property.
AttributeCollection^ attributes = TypeDescriptor::GetProperties( this )[ "MyProperty" ]->Attributes;
/* Prints the default value by retrieving the DefaultValueAttribute
* from the AttributeCollection. */
DefaultValueAttribute^ myAttribute = dynamic_cast<DefaultValueAttribute^>(attributes[ DefaultValueAttribute::typeid ]);
Console::WriteLine( "The default value is: {0}", myAttribute->Value );
// Gets the attributes for the property.
AttributeCollection attributes =
TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
/* Prints the default value by retrieving the DefaultValueAttribute
* from the AttributeCollection. */
DefaultValueAttribute myAttribute =
(DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];
Console.WriteLine("The default value is: " + myAttribute.Value.ToString());
' Gets the attributes for the property.
Dim attributes As AttributeCollection =
TypeDescriptor.GetProperties(Me)("MyProperty").Attributes
' Prints the default value by retrieving the DefaultValueAttribute
' from the AttributeCollection.
Dim myAttribute As DefaultValueAttribute =
CType(attributes(GetType(DefaultValueAttribute)), DefaultValueAttribute)
Console.WriteLine(("The default value is: " & myAttribute.Value.ToString()))
Comentários
Você pode criar um DefaultValueAttribute com qualquer valor. Normalmente, o valor padrão de um membro é seu valor inicial. Um designer visual pode usar o valor padrão para redefinir o valor do membro. Os geradores de código também podem usar os valores padrão para determinar se o código deve ser gerado para o membro.
Note
Um DefaultValueAttribute não fará com que um membro seja inicializado automaticamente com o valor do atributo. Você deve definir o valor inicial em seu código.
Para obter mais informações, consulte Atributos.
Construtores
| Nome | Description |
|---|---|
| DefaultValueAttribute(Boolean) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um Boolean valor. |
| DefaultValueAttribute(Byte) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um inteiro sem sinal de 8 bits. |
| DefaultValueAttribute(Char) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um caractere Unicode. |
| DefaultValueAttribute(Double) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um número de ponto flutuante de precisão dupla. |
| DefaultValueAttribute(Int16) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um inteiro com sinal de 16 bits. |
| DefaultValueAttribute(Int32) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um inteiro com sinal de 32 bits. |
| DefaultValueAttribute(Int64) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um inteiro com sinal de 64 bits. |
| DefaultValueAttribute(Object) |
Inicializa uma nova instância da classe DefaultValueAttribute. |
| DefaultValueAttribute(SByte) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um SByte valor. |
| DefaultValueAttribute(Single) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um número de ponto flutuante de precisão única. |
| DefaultValueAttribute(String) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um String. |
| DefaultValueAttribute(Type, String) |
Inicializa uma nova instância da DefaultValueAttribute classe, convertendo o valor especificado no tipo especificado e usando uma cultura invariável como o contexto de tradução. |
| DefaultValueAttribute(UInt16) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um UInt16 valor. |
| DefaultValueAttribute(UInt32) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um UInt32 valor. |
| DefaultValueAttribute(UInt64) |
Inicializa uma nova instância da DefaultValueAttribute classe usando um UInt64 valor. |
Propriedades
| Nome | Description |
|---|---|
| TypeId |
Quando implementado em uma classe derivada, obtém um identificador exclusivo para esse Attribute. (Herdado de Attribute) |
| Value |
Obtém o valor padrão da propriedade à qual esse atributo está associado. |
Métodos
| Nome | Description |
|---|---|
| Equals(Object) |
Retorna se o valor do objeto fornecido é igual ao atual DefaultValueAttribute. |
| GetHashCode() |
Retorna o código hash dessa instância. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| IsDefaultAttribute() |
Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada. (Herdado de Attribute) |
| Match(Object) |
Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado. (Herdado de Attribute) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| SetValue(Object) |
Define o valor padrão da propriedade à qual esse atributo está associado. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual. (Herdado de Object) |
Implantações explícitas de interface
| Nome | Description |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição. (Herdado de Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera as informações de tipo de um objeto, que podem ser usadas para obter as informações de tipo de uma interface. (Herdado de Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1). (Herdado de Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornece acesso a propriedades e métodos expostos por um objeto. (Herdado de Attribute) |