ReadOnlyAttribute Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Especifica se a propriedade a que este atributo está associado é só leitura ou leitura/escrita. Esta classe não pode ser herdada.
public ref class ReadOnlyAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.All)]
public sealed class ReadOnlyAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.All)>]
type ReadOnlyAttribute = class
inherit Attribute
Public NotInheritable Class ReadOnlyAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
O seguinte exemplo de código marca uma propriedade como apenas de 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 para MyProperty. Primeiro, o código recebe a PropertyDescriptorCollection com todas as propriedades do objeto. De seguida, indexa para obter PropertyDescriptorCollectionMyProperty. Depois, devolve os atributos dessa propriedade e guarda-os na variável de atributos.
O exemplo apresenta duas formas 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 marcou uma classe com o ReadOnlyAttribute, use o seguinte exemplo de código 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
Observações
Os membros que estão marcados com o ReadOnlyAttribute conjunto como true ou que não têm método Set não podem ser alterados. Os membros que não têm este atributo ou que estão marcados com o ReadOnlyAttribute conjunto para false são lidos/escritos, e podem ser alterados. A predefinição é No.
Importante
A PropertyDescriptor classe impõe o ReadOnlyAttribute no ambiente de design e em tempo de execução. Quando se marca uma propriedade com o ReadOnlyAttribute conjunto em true, o valor deste atributo é definido para o elemento Yesconstante . Para uma propriedade marcada com o ReadOnlyAttribute conjunto de , falseo valor é No. Portanto, quando quiser verificar o valor deste atributo no seu código, deve especificar o atributo como ReadOnlyAttribute.Yes ou ReadOnlyAttribute.No.
Para obter mais informações, consulte Atributos.
Construtores
| Name | Description |
|---|---|
| ReadOnlyAttribute(Boolean) |
Inicializa uma nova instância da ReadOnlyAttribute classe. |
Campos
| Name | Description |
|---|---|
| Default |
Especifica o valor padrão para o ReadOnlyAttribute, que é No (isto é, a propriedade a que este atributo está ligado é leitura/escrita). Este |
| No |
Especifica que a propriedade a que este atributo está ligado é leitura/escrita e pode ser modificada. Este |
| Yes |
Especifica que a propriedade a que este atributo está ligado é apenas de leitura e não pode ser modificada no explorador do servidor. Este |
Propriedades
| Name | Description |
|---|---|
| IsReadOnly |
Recebe um valor que indica se a propriedade a que este atributo está ligado é apenas de leitura. |
| TypeId |
Quando implementado numa classe derivada, obtém um identificador único para esta Attribute. (Herdado de Attribute) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Indica se esta instância e um objeto especificado são iguais. |
| GetHashCode() |
Devolve o código de hash para esta instância. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| IsDefaultAttribute() |
Determina se este atributo é o padrão. |
| Match(Object) |
Quando sobrescrito numa classe derivada, devolve um valor que indica se esta instância é igual a um objeto especificado. (Herdado de Attribute) |
| 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 |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de despacho. (Herdado de Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera a informação de tipo de um objeto, que pode ser usada para obter a informação de tipo para uma interface. (Herdado de Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Recupera o número de interfaces de informações de tipo que um objeto fornece (0 ou 1). (Herdado de Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Proporciona acesso a propriedades e métodos expostos por um objeto. (Herdado de Attribute) |