PropertyDescriptor Classe

Definição

Fornece uma abstração de uma propriedade sobre uma classe.

public ref class PropertyDescriptor abstract : System::ComponentModel::MemberDescriptor
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class PropertyDescriptor : System.ComponentModel.MemberDescriptor
public abstract class PropertyDescriptor : System.ComponentModel.MemberDescriptor
[<System.Runtime.InteropServices.ComVisible(true)>]
type PropertyDescriptor = class
    inherit MemberDescriptor
type PropertyDescriptor = class
    inherit MemberDescriptor
Public MustInherit Class PropertyDescriptor
Inherits MemberDescriptor
Herança
PropertyDescriptor
Derivado
Atributos

Exemplos

O seguinte exemplo de código é construído sobre o exemplo da PropertyDescriptorCollection classe. Imprime a informação (categoria, descrição, nome de visualização) do texto de um botão numa caixa de texto. Assume que button1 e textbox1 foram instanciados num formulário.

// Creates a new collection and assign it the properties for button1.
PropertyDescriptorCollection^ properties = TypeDescriptor::GetProperties( button1 );

// Sets an PropertyDescriptor to the specific property.
System::ComponentModel::PropertyDescriptor^ myProperty = properties->Find( "Text", false );

// Prints the property and the property description.
textBox1->Text = String::Concat( myProperty->DisplayName, "\n" );
textBox1->Text = String::Concat( textBox1->Text, myProperty->Description, "\n" );
textBox1->Text = String::Concat( textBox1->Text, myProperty->Category, "\n" );
// Creates a new collection and assign it the properties for button1.
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);

// Sets an PropertyDescriptor to the specific property.
PropertyDescriptor myProperty = properties.Find("Text", false);

// Prints the property and the property description.
textBox1.Text = myProperty.DisplayName + '\n';
textBox1.Text += myProperty.Description + '\n';
textBox1.Text += myProperty.Category + '\n';
' Creates a new collection and assign it the properties for button1.
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(Button1)

' Sets an PropertyDescriptor to the specific property.
Dim myProperty As PropertyDescriptor = properties.Find("Text", False)

' Prints the property and the property description.
TextBox1.Text += myProperty.DisplayName & ControlChars.Cr
TextBox1.Text += myProperty.Description & ControlChars.Cr
TextBox1.Text += myProperty.Category & ControlChars.Cr

O exemplo de código seguinte mostra como implementar um descritor de propriedade personalizado que fornece um wrapper de apenas leitura em torno de uma propriedade. O SerializeReadOnlyPropertyDescriptor é usado num designer personalizado para fornecer um descritor de propriedade apenas de leitura para a propriedade do Size controlo.

using System;
using System.Collections;
using System.ComponentModel;

namespace ReadOnlyPropertyDescriptorTest;

// The SerializeReadOnlyPropertyDescriptor shows how to implement a 
// custom property descriptor. It provides a read-only wrapper 
// around the specified PropertyDescriptor. 
sealed class SerializeReadOnlyPropertyDescriptor : PropertyDescriptor
{
    readonly PropertyDescriptor _pd;

    public SerializeReadOnlyPropertyDescriptor(PropertyDescriptor pd)
        : base(pd) => _pd = pd;

    public override AttributeCollection Attributes => AppendAttributeCollection(
                _pd.Attributes,
                ReadOnlyAttribute.Yes);

    protected override void FillAttributes(IList attributeList) => attributeList.Add(ReadOnlyAttribute.Yes);

    public override Type ComponentType => _pd.ComponentType;

    // The type converter for this property.
    // A translator can overwrite with its own converter.
    public override TypeConverter Converter => _pd.Converter;

    // Returns the property editor 
    // A translator can overwrite with its own editor.
    public override object GetEditor(Type editorBaseType) => _pd.GetEditor(editorBaseType);

    // Specifies the property is read only.
    public override bool IsReadOnly => true;

    public override Type PropertyType => _pd.PropertyType;

    public override bool CanResetValue(object component) => _pd.CanResetValue(component);

    public override object GetValue(object component) => _pd.GetValue(component);

    public override void ResetValue(object component) => _pd.ResetValue(component);

    public override void SetValue(object component, object val) => _pd.SetValue(component, val);

    // Determines whether a value should be serialized.
    public override bool ShouldSerializeValue(object component)
    {
        bool result = _pd.ShouldSerializeValue(component);

        if (!result)
        {
            DefaultValueAttribute dva = (DefaultValueAttribute)_pd.Attributes[typeof(DefaultValueAttribute)];
            result = dva == null || !Equals(_pd.GetValue(component), dva.Value);
        }

        return result;
    }

    // The following Utility methods create a new AttributeCollection
    // by appending the specified attributes to an existing collection.
    public static AttributeCollection AppendAttributeCollection(
        AttributeCollection existing,
        params Attribute[] newAttrs) => new(AppendAttributes(existing, newAttrs));

    public static Attribute[] AppendAttributes(
        AttributeCollection existing,
        params Attribute[] newAttrs)
    {
        if (existing == null)
        {
            throw new ArgumentNullException(nameof(existing));
        }

        newAttrs ??= [];

        Attribute[] attributes;

        Attribute[] newArray = new Attribute[existing.Count + newAttrs.Length];
        int actualCount = existing.Count;
        existing.CopyTo(newArray, 0);

        for (int idx = 0; idx < newAttrs.Length; idx++)
        {
            if (newAttrs[idx] == null)
            {
                throw new ArgumentNullException(nameof(newAttrs));
            }

            // Check if this attribute is already in the existing
            // array.  If it is, replace it.
            bool match = false;
            for (int existingIdx = 0; existingIdx < existing.Count; existingIdx++)
            {
                if (newArray[existingIdx].TypeId.Equals(newAttrs[idx].TypeId))
                {
                    match = true;
                    newArray[existingIdx] = newAttrs[idx];
                    break;
                }
            }

            if (!match)
            {
                newArray[actualCount++] = newAttrs[idx];
            }
        }

        // If some attributes were collapsed, create a new array.
        if (actualCount < newArray.Length)
        {
            attributes = new Attribute[actualCount];
            Array.Copy(newArray, 0, attributes, 0, actualCount);
        }
        else
        {
            attributes = newArray;
        }

        return attributes;
    }
}
Imports System.Collections
Imports System.ComponentModel
Imports System.Text

' The SerializeReadOnlyPropertyDescriptor shows how to implement a 
' custom property descriptor. It provides a read-only wrapper 
' around the specified PropertyDescriptor. 
Friend NotInheritable Class SerializeReadOnlyPropertyDescriptor
    Inherits PropertyDescriptor
    Private _pd As PropertyDescriptor = Nothing


    Public Sub New(ByVal pd As PropertyDescriptor)
        MyBase.New(pd)
        Me._pd = pd

    End Sub


    Public Overrides ReadOnly Property Attributes() As AttributeCollection
        Get
            Return AppendAttributeCollection(Me._pd.Attributes, ReadOnlyAttribute.Yes)
        End Get
    End Property


    Protected Overrides Sub FillAttributes(ByVal attributeList As IList)
        attributeList.Add(ReadOnlyAttribute.Yes)

    End Sub


    Public Overrides ReadOnly Property ComponentType() As Type
        Get
            Return Me._pd.ComponentType
        End Get
    End Property


    ' The type converter for this property.
    ' A translator can overwrite with its own converter.
    Public Overrides ReadOnly Property Converter() As TypeConverter
        Get
            Return Me._pd.Converter
        End Get
    End Property


    ' Returns the property editor 
    ' A translator can overwrite with its own editor.
    Public Overrides Function GetEditor(ByVal editorBaseType As Type) As Object
        Return Me._pd.GetEditor(editorBaseType)

    End Function

    ' Specifies the property is read only.
    Public Overrides ReadOnly Property IsReadOnly() As Boolean
        Get
            Return True
        End Get
    End Property


    Public Overrides ReadOnly Property PropertyType() As Type
        Get
            Return Me._pd.PropertyType
        End Get
    End Property


    Public Overrides Function CanResetValue(ByVal component As Object) As Boolean
        Return Me._pd.CanResetValue(component)

    End Function


    Public Overrides Function GetValue(ByVal component As Object) As Object
        Return Me._pd.GetValue(component)

    End Function


    Public Overrides Sub ResetValue(ByVal component As Object)
        Me._pd.ResetValue(component)

    End Sub


    Public Overrides Sub SetValue(ByVal component As Object, ByVal val As Object)
        Me._pd.SetValue(component, val)

    End Sub

    ' Determines whether a value should be serialized.
    Public Overrides Function ShouldSerializeValue(ByVal component As Object) As Boolean
        Dim result As Boolean = Me._pd.ShouldSerializeValue(component)

        If Not result Then
            Dim dva As DefaultValueAttribute = _
                CType(_pd.Attributes(GetType(DefaultValueAttribute)), DefaultValueAttribute)
            If Not (dva Is Nothing) Then
                result = Not [Object].Equals(Me._pd.GetValue(component), dva.Value)
            Else
                result = True
            End If
        End If

        Return result

    End Function


    ' The following Utility methods create a new AttributeCollection
    ' by appending the specified attributes to an existing collection.
    Public Shared Function AppendAttributeCollection( _
        ByVal existing As AttributeCollection, _
        ByVal ParamArray newAttrs() As Attribute) As AttributeCollection

        Return New AttributeCollection(AppendAttributes(existing, newAttrs))

    End Function

    Public Shared Function AppendAttributes( _
        ByVal existing As AttributeCollection, _
        ByVal ParamArray newAttrs() As Attribute) As Attribute()

        If existing Is Nothing Then
            Throw New ArgumentNullException("existing")
        End If

        If newAttrs Is Nothing Then
            newAttrs = New Attribute(-1) {}
        End If

        Dim attributes() As Attribute

        Dim newArray(existing.Count + newAttrs.Length) As Attribute
        Dim actualCount As Integer = existing.Count
        existing.CopyTo(newArray, 0)

        Dim idx As Integer
        For idx = 0 To newAttrs.Length
            If newAttrs(idx) Is Nothing Then
                Throw New ArgumentNullException("newAttrs")
            End If

            ' Check if this attribute is already in the existing
            ' array.  If it is, replace it.
            Dim match As Boolean = False
            Dim existingIdx As Integer
            For existingIdx = 0 To existing.Count - 1
                If newArray(existingIdx).TypeId.Equals(newAttrs(idx).TypeId) Then
                    match = True
                    newArray(existingIdx) = newAttrs(idx)
                    Exit For
                End If
            Next existingIdx

            If Not match Then
                actualCount += 1
                newArray(actualCount) = newAttrs(idx)
            End If
        Next idx

        ' If some attributes were collapsed, create a new array.
        If actualCount < newArray.Length Then
            attributes = New Attribute(actualCount) {}
            Array.Copy(newArray, 0, attributes, 0, actualCount)
        Else
            attributes = newArray
        End If

        Return attributes

    End Function
End Class

Os seguintes exemplos de código mostram como usar o SerializeReadOnlyPropertyDescriptor num designer personalizado.

using System.Collections;
using System.ComponentModel;
using System.Windows.Forms.Design;

namespace ReadOnlyPropertyDescriptorTest;

class DemoControlDesigner : ControlDesigner
{
    // The PostFilterProperties method replaces the control's 
    // Size property with a read-only Size property by using 
    // the SerializeReadOnlyPropertyDescriptor class.
    protected override void PostFilterProperties(IDictionary properties)
    {
        if (properties.Contains("Size"))
        {
            PropertyDescriptor original = properties["Size"] as PropertyDescriptor;
            SerializeReadOnlyPropertyDescriptor readOnlyDescriptor =
                new(original);

            properties["Size"] = readOnlyDescriptor;
        }

        base.PostFilterProperties(properties);
    }
}
Imports System.Collections
Imports System.ComponentModel
Imports System.Text
Imports System.Windows.Forms.Design

Class DemoControlDesigner
    Inherits ControlDesigner
    
    ' The PostFilterProperties method replaces the control's 
    ' Size property with a read-only Size property by using 
    ' the SerializeReadOnlyPropertyDescriptor class.
    Protected Overrides Sub PostFilterProperties(ByVal properties As IDictionary) 
        If properties.Contains("Size") Then
            Dim original As PropertyDescriptor = properties("Size")
            
            Dim readOnlyDescriptor As New SerializeReadOnlyPropertyDescriptor(original)
            
            properties("Size") = readOnlyDescriptor
        End If
        
        MyBase.PostFilterProperties(properties)
    
    End Sub
End Class
using System.ComponentModel;
using System.Windows.Forms;

namespace ReadOnlyPropertyDescriptorTest;

[Designer(typeof(DemoControlDesigner))]
public class DemoControl : Control
{
    public DemoControl()
    {
    }
}
Imports System.ComponentModel
Imports System.Windows.Forms

<Designer(GetType(DemoControlDesigner))>
Public Class DemoControl
    Inherits Control

    Public Sub New()

    End Sub
End Class

Observações

Uma descrição de uma propriedade consiste num nome, os seus atributos, a classe de componentes a que a propriedade está associada e o tipo da propriedade.

PropertyDescriptor fornece as seguintes propriedades e métodos:

PropertyDescriptor também fornece as seguintes abstract propriedades e métodos:

  • ComponentType contém o tipo de componente a que esta propriedade está ligada.

  • IsReadOnly indica se esta propriedade é de apenas leitura.

  • PropertyType Percebe o tipo de propriedade.

  • CanResetValue indica se reiniciar o componente altera o valor do componente.

  • GetValue devolve o valor atual da propriedade num componente.

  • ResetValue redefine o valor desta propriedade do componente.

  • SetValue define o valor do componente para um valor diferente.

  • ShouldSerializeValue indica se o valor desta propriedade precisa de ser mantido.

Normalmente, os abstract membros são implementados através da reflexão. Para mais informações sobre reflexão, consulte os tópicos em Reflexão.

Construtores

Name Description
PropertyDescriptor(MemberDescriptor, Attribute[])

Inicializa uma nova instância da PropertyDescriptor classe com o nome no especificado MemberDescriptor e os atributos tanto no MemberDescriptor como no Attribute array.

PropertyDescriptor(MemberDescriptor)

Inicializa uma nova instância da PropertyDescriptor classe com o nome e os atributos no especificado MemberDescriptor.

PropertyDescriptor(String, Attribute[])

Inicializa uma nova instância da PropertyDescriptor classe com o nome e atributos especificados.

Propriedades

Name Description
AttributeArray

Obtém ou define um conjunto de atributos.

(Herdado de MemberDescriptor)
Attributes

Obtém a coleção de atributos deste membro.

(Herdado de MemberDescriptor)
Category

Obtém o nome da categoria à qual o membro pertence, conforme especificado no CategoryAttribute.

(Herdado de MemberDescriptor)
ComponentType

Quando sobrescrito numa classe derivada, obtém o tipo do componente a que esta propriedade está ligada.

Converter

Obtém o conversor de tipos para esta propriedade.

Description

Obtém a descrição do membro, conforme especificado no DescriptionAttribute.

(Herdado de MemberDescriptor)
DesignTimeOnly

Obtém se este elemento deve ser definido apenas na altura do projeto, conforme especificado no DesignOnlyAttribute.

(Herdado de MemberDescriptor)
DisplayName

Recebe o nome que pode ser exibido numa janela, como uma janela Propriedades.

(Herdado de MemberDescriptor)
IsBrowsable

Obtém um valor que indica se o membro é navegável, conforme especificado no BrowsableAttribute.

(Herdado de MemberDescriptor)
IsLocalizable

Obtém um valor que indica se esta propriedade deve ser localizada, conforme especificado no LocalizableAttribute.

IsReadOnly

Quando sobrescrito numa classe derivada, obtém um valor que indica se esta propriedade é apenas de leitura.

Name

Obtém o nome do membro.

(Herdado de MemberDescriptor)
NameHashCode

Obtém o código de hash para o nome do membro, conforme especificado em GetHashCode().

(Herdado de MemberDescriptor)
PropertyType

Quando sobrescrito numa classe derivada, obtém o tipo da propriedade.

SerializationVisibility

Obtém um valor que indica se esta propriedade deve ser serializada, conforme especificado no DesignerSerializationVisibilityAttribute.

SupportsChangeEvents

Recebe um valor que indica se as notificações de alteração de valor para esta propriedade podem ter origem fora do descritor da propriedade.

Métodos

Name Description
AddValueChanged(Object, EventHandler)

Permite que outros objetos sejam notificados quando esta propriedade muda.

CanResetValue(Object)

Quando sobrescrito numa classe derivada, devolve se o reset de um objeto altera o seu valor.

CreateAttributeCollection()

Cria uma coleção de atributos usando o array de atributos passados ao construtor.

(Herdado de MemberDescriptor)
CreateInstance(Type)

Cria uma instância do tipo especificado.

Equals(Object)

Compara isto com outro objeto para ver se são equivalentes.

FillAttributes(IList)

Adiciona os atributos de à PropertyDescriptor lista especificada de atributos na classe pai.

FillAttributes(IList)

Quando sobreposto numa classe derivada, adiciona os atributos da classe herdeira à lista especificada de atributos na classe mãe.

(Herdado de MemberDescriptor)
GetChildProperties()

Devolve o valor padrão PropertyDescriptorCollection.

GetChildProperties(Attribute[])

Devolve a PropertyDescriptorCollection usando um array especificado de atributos como filtro.

GetChildProperties(Object, Attribute[])

Devolve a PropertyDescriptorCollection para um dado objeto usando um array especificado de atributos como filtro.

GetChildProperties(Object)

Devolve a PropertyDescriptorCollection para um dado objeto.

GetEditor(Type)

Recebe um editor do tipo especificado.

GetHashCode()

Devolve o código de hash deste objeto.

GetInvocationTarget(Type, Object)

Este método devolve o objeto que deve ser usado durante a invocação dos membros.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
GetTypeFromName(String)

Devolve um tipo usando o seu nome.

GetValue(Object)

Quando sobrescrito numa classe derivada, obtém o valor atual da propriedade num componente.

GetValueChangedHandler(Object)

Recupera o conjunto atual de ValueChanged gestores de eventos para um componente específico.

MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
OnValueChanged(Object, EventArgs)

Aumenta o ValueChanged evento que implementaste.

RemoveValueChanged(Object, EventHandler)

Permite que outros objetos sejam notificados quando esta propriedade muda.

ResetValue(Object)

Quando sobrescrito numa classe derivada, redefine o valor desta propriedade do componente para o valor padrão.

SetValue(Object, Object)

Quando sobrescrito numa classe derivada, define o valor do componente para um valor diferente.

ShouldSerializeValue(Object)

Quando sobrescrito numa classe derivada, determina um valor que indica se o valor desta propriedade precisa de ser mantido.

ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Ver também