ReadOnlyAttribute 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 se a propriedade à qual esse atributo está associado é somente leitura ou leitura/gravação. Essa classe não pode ser herdada.
public ref class ReadOnlyAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.All)]
public sealed class ReadOnlyAttribute : Attribute
public sealed class ReadOnlyAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.All)>]
type ReadOnlyAttribute = class
inherit Attribute
type ReadOnlyAttribute = class
inherit Attribute
Public NotInheritable Class ReadOnlyAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
O exemplo de código a seguir marca uma propriedade como somente leitura.
[ReadOnly(true)]
int get()
{
// Insert code here.
return 0;
}
}
[ReadOnly(true)]
public int MyProperty =>
// Insert code here.
0;
Public ReadOnly Property MyProperty() As Integer
Get
' Insert code here.
Return 0
End Get
End Property
O próximo exemplo de código mostra como verificar o valor do ReadOnlyAttribute .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.
O exemplo apresenta duas maneiras diferentes de verificar o valor do ReadOnlyAttribute. No segundo fragmento de código, o exemplo chama o Equals método. No último fragmento de código, o exemplo usa a IsReadOnly propriedade para verificar o valor.
// Gets the attributes for the property.
AttributeCollection^ attributes = TypeDescriptor::GetProperties( this )[ "MyProperty" ]->Attributes;
// Checks to see whether the value of the ReadOnlyAttribute is Yes.
if ( attributes[ ReadOnlyAttribute::typeid ]->Equals( ReadOnlyAttribute::Yes ) )
{
// Insert code here.
}
// This is another way to see whether the property is read-only.
ReadOnlyAttribute^ myAttribute = dynamic_cast<ReadOnlyAttribute^>(attributes[ ReadOnlyAttribute::typeid ]);
if ( myAttribute->IsReadOnly )
{
// Insert code here.
}
// Gets the attributes for the property.
AttributeCollection attributes =
TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
// Checks to see whether the value of the ReadOnlyAttribute is Yes.
if (attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes))
{
// Insert code here.
}
// This is another way to see whether the property is read-only.
ReadOnlyAttribute myAttribute =
(ReadOnlyAttribute)attributes[typeof(ReadOnlyAttribute)];
if (myAttribute.IsReadOnly)
{
// Insert code here.
}
' Gets the attributes for the property.
Dim attributes As AttributeCollection = _
TypeDescriptor.GetProperties(Me)("MyProperty").Attributes
' Checks to see whether the value of the ReadOnlyAttribute is Yes.
If attributes(GetType(ReadOnlyAttribute)).Equals(ReadOnlyAttribute.Yes) Then
' Insert code here.
End If
' This is another way to see whether the property is read-only.
Dim myAttribute As ReadOnlyAttribute = _
CType(attributes(GetType(ReadOnlyAttribute)), ReadOnlyAttribute)
If myAttribute.IsReadOnly Then
' Insert code here.
End If
Se você marcou uma classe com a ReadOnlyAttribute, use o exemplo de código a seguir para verificar o valor.
AttributeCollection^ attributes = TypeDescriptor::GetAttributes( MyProperty );
if ( attributes[ ReadOnlyAttribute::typeid ]->Equals( ReadOnlyAttribute::Yes ) )
{
// Insert code here.
}
AttributeCollection attributes =
TypeDescriptor.GetAttributes(MyProperty);
if (attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes))
{
// Insert code here.
}
Dim attributes As AttributeCollection = TypeDescriptor.GetAttributes(MyProperty)
If attributes(GetType(ReadOnlyAttribute)).Equals(ReadOnlyAttribute.Yes) Then
' Insert code here.
End If
Comentários
Os membros marcados com o ReadOnlyAttribute conjunto para true ou que não têm um Set método não podem ser alterados. Os membros que não têm esse atributo ou que estão marcados com o ReadOnlyAttribute conjunto para false leitura/gravação, podem ser alterados. O padrão é No.
Importante
A PropertyDescriptor classe impõe o ReadOnlyAttribute ambiente de design e em tempo de execução. Quando você marca uma propriedade com o ReadOnlyAttribute conjunto como true, o valor desse atributo é definido como o membro Yesconstante. Para uma propriedade marcada com o ReadOnlyAttribute conjunto como false, o valor é No. Portanto, quando você deseja verificar o valor desse atributo em seu código, você deve especificar o atributo como ReadOnlyAttribute.Yes ou ReadOnlyAttribute.No.
Para obter mais informações, consulte Atributos.
Construtores
| Nome | Description |
|---|---|
| ReadOnlyAttribute(Boolean) |
Inicializa uma nova instância da classe ReadOnlyAttribute. |
Campos
| Nome | Description |
|---|---|
| Default |
Especifica o valor padrão para o ReadOnlyAttribute, ou seja No , a propriedade à qual esse atributo está associado é leitura/gravação). Este |
| No |
Especifica que a propriedade à qual esse atributo está associado é de leitura/gravação e pode ser modificada. Este |
| Yes |
Especifica que a propriedade à qual esse atributo está associado é somente leitura e não pode ser modificada no gerenciador de servidores. Este |
Propriedades
| Nome | Description |
|---|---|
| IsReadOnly |
Obtém um valor que indica se a propriedade à qual esse atributo está associado é somente leitura. |
| TypeId |
Quando implementado em uma classe derivada, obtém um identificador exclusivo para esse Attribute. (Herdado de Attribute) |
Métodos
| Nome | Description |
|---|---|
| Equals(Object) |
Indica se essa instância e um objeto especificado são iguais. |
| GetHashCode() |
Retorna o código hash dessa instância. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| IsDefaultAttribute() |
Determina se esse atributo é o padrão. |
| 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) |
| 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) |