Condividi tramite


PropertyDescriptor Classe

Definizione

Fornisce un'astrazione di una proprietà in una classe .

public ref class PropertyDescriptor abstract : System::ComponentModel::MemberDescriptor
public abstract class PropertyDescriptor : System.ComponentModel.MemberDescriptor
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class PropertyDescriptor : System.ComponentModel.MemberDescriptor
type PropertyDescriptor = class
    inherit MemberDescriptor
[<System.Runtime.InteropServices.ComVisible(true)>]
type PropertyDescriptor = class
    inherit MemberDescriptor
Public MustInherit Class PropertyDescriptor
Inherits MemberDescriptor
Ereditarietà
PropertyDescriptor
Derivato
Attributi

Esempio

L'esempio di codice seguente è basato sull'esempio nella PropertyDescriptorCollection classe . Stampa le informazioni (categoria, descrizione, nome visualizzato) del testo di un pulsante in una casella di testo. Si presuppone che button1 e textbox1 sia stata creata un'istanza in un modulo.

// 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

Nell'esempio di codice seguente viene illustrato come implementare un descrittore di proprietà personalizzato che fornisce un wrapper di sola lettura intorno a una proprietà. Viene SerializeReadOnlyPropertyDescriptor utilizzato in una finestra di progettazione personalizzata per fornire un descrittore di proprietà di sola lettura per la proprietà del Size controllo.

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

Negli esempi di codice seguenti viene illustrato come usare SerializeReadOnlyPropertyDescriptor in una finestra di progettazione personalizzata.

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

Commenti

Una descrizione di una proprietà è costituita da un nome, dai relativi attributi, dalla classe componente a cui è associata la proprietà e dal tipo della proprietà.

PropertyDescriptor fornisce le proprietà e i metodi seguenti:

PropertyDescriptor fornisce anche le proprietà e i metodi seguenti abstract :

  • ComponentType contiene il tipo di componente a cui questa proprietà è associata.

  • IsReadOnly indica se questa proprietà è di sola lettura.

  • PropertyType ottiene il tipo della proprietà .

  • CanResetValue indica se la reimpostazione del componente modifica il valore del componente.

  • GetValue restituisce il valore corrente della proprietà in un componente.

  • ResetValue reimposta il valore per questa proprietà del componente.

  • SetValue imposta il valore del componente su un valore diverso.

  • ShouldSerializeValue indica se il valore di questa proprietà deve essere salvato in modo permanente.

In genere, i abstract membri vengono implementati tramite reflection. Per altre informazioni sulla reflection, vedere gli argomenti in Reflection.

Costruttori

Nome Descrizione
PropertyDescriptor(MemberDescriptor, Attribute[])

Inizializza una nuova istanza della PropertyDescriptor classe con il nome nell'oggetto specificato MemberDescriptor e gli attributi nella MemberDescriptor matrice e Attribute .

PropertyDescriptor(MemberDescriptor)

Inizializza una nuova istanza della PropertyDescriptor classe con il nome e gli attributi nell'oggetto specificato MemberDescriptor.

PropertyDescriptor(String, Attribute[])

Inizializza una nuova istanza della PropertyDescriptor classe con il nome e gli attributi specificati.

Proprietà

Nome Descrizione
AttributeArray

Ottiene o imposta una matrice di attributi.

(Ereditato da MemberDescriptor)
Attributes

Ottiene la raccolta di attributi per questo membro.

(Ereditato da MemberDescriptor)
Category

Ottiene il nome della categoria a cui appartiene il membro, come specificato in CategoryAttribute.

(Ereditato da MemberDescriptor)
ComponentType

Quando sottoposto a override in una classe derivata, ottiene il tipo del componente a cui è associata questa proprietà.

Converter

Ottiene il convertitore di tipi per questa proprietà.

ConverterFromRegisteredType

Ottiene il convertitore di tipi per questa proprietà.

Description

Ottiene la descrizione del membro, come specificato in DescriptionAttribute.

(Ereditato da MemberDescriptor)
DesignTimeOnly

Ottiene un valore che indica se questo membro deve essere impostato solo in fase di progettazione, come specificato in DesignOnlyAttribute.

(Ereditato da MemberDescriptor)
DisplayName

Ottiene il nome che può essere visualizzato in una finestra, ad esempio una finestra Proprietà.

(Ereditato da MemberDescriptor)
IsBrowsable

Ottiene un valore che indica se il membro è esplorabile, come specificato in BrowsableAttribute.

(Ereditato da MemberDescriptor)
IsLocalizable

Ottiene un valore che indica se questa proprietà deve essere localizzata, come specificato in LocalizableAttribute.

IsReadOnly

In caso di override in una classe derivata, ottiene un valore che indica se questa proprietà è di sola lettura.

Name

Ottiene il nome del membro.

(Ereditato da MemberDescriptor)
NameHashCode

Ottiene il codice hash per il nome del membro, come specificato in GetHashCode().

(Ereditato da MemberDescriptor)
PropertyType

In caso di override in una classe derivata, ottiene il tipo della proprietà .

SerializationVisibility

Ottiene un valore che indica se questa proprietà deve essere serializzata, come specificato in DesignerSerializationVisibilityAttribute.

SupportsChangeEvents

Ottiene un valore che indica se le notifiche di modifica del valore per questa proprietà possono provenire dall'esterno del descrittore della proprietà.

Metodi

Nome Descrizione
AddValueChanged(Object, EventHandler)

Consente ad altri oggetti di ricevere una notifica quando questa proprietà viene modificata.

CanResetValue(Object)

Quando sottoposto a override in una classe derivata, restituisce se la reimpostazione di un oggetto ne modifica il valore.

CreateAttributeCollection()

Crea una raccolta di attributi usando la matrice di attributi passati al costruttore.

(Ereditato da MemberDescriptor)
CreateInstance(Type)

Crea un'istanza del tipo specificato.

Equals(Object)

Confronta questo oggetto con un altro oggetto per verificare se sono equivalenti.

FillAttributes(IList)

Aggiunge gli attributi dell'oggetto PropertyDescriptor all'elenco di attributi specificato nella classe padre.

FillAttributes(IList)

Quando sottoposto a override in una classe derivata, aggiunge gli attributi della classe che eredita all'elenco di attributi specificato nella classe padre.

(Ereditato da MemberDescriptor)
GetChildProperties()

Restituisce l'oggetto predefinito PropertyDescriptorCollection.

GetChildProperties(Attribute[])

Restituisce un PropertyDescriptorCollection oggetto utilizzando una matrice di attributi specificata come filtro.

GetChildProperties(Object, Attribute[])

Restituisce un oggetto PropertyDescriptorCollection per un determinato oggetto utilizzando una matrice di attributi specificata come filtro.

GetChildProperties(Object)

Restituisce un oggetto PropertyDescriptorCollection per un determinato oggetto.

GetEditor(Type)

Ottiene un editor del tipo specificato.

GetHashCode()

Restituisce il codice hash per questo oggetto.

GetInvocationTarget(Type, Object)

Questo metodo restituisce l'oggetto che deve essere utilizzato durante la chiamata dei membri.

GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
GetTypeFromName(String)

Restituisce un tipo utilizzando il relativo nome.

GetValue(Object)

Quando sottoposto a override in una classe derivata, ottiene il valore corrente della proprietà in un componente.

GetValueChangedHandler(Object)

Recupera il set corrente di gestori eventi ValueChanged per un componente specifico.

MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
OnValueChanged(Object, EventArgs)

Genera l'evento ValueChanged implementato.

RemoveValueChanged(Object, EventHandler)

Consente ad altri oggetti di ricevere una notifica quando questa proprietà viene modificata.

ResetValue(Object)

Quando sottoposto a override in una classe derivata, reimposta il valore per questa proprietà del componente sul valore predefinito.

SetValue(Object, Object)

Quando sottoposto a override in una classe derivata, imposta il valore del componente su un valore diverso.

ShouldSerializeValue(Object)

In caso di override in una classe derivata, determina un valore che indica se il valore di questa proprietà deve essere salvato in modo permanente.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a

Vedi anche