PropertyDescriptor 类

定义

提供类的属性的抽象。

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
继承
PropertyDescriptor
派生
属性

示例

下面的代码示例基于类中的 PropertyDescriptorCollection 示例生成。 它会打印文本框中按钮文本 (类别、说明、显示名称) 的信息。 它假定 button1 已在 textbox1 窗体上实例化。

// 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.
System.ComponentModel.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 & Microsoft.VisualBasic.ControlChars.Cr
TextBox1.Text += myProperty.Description & Microsoft.VisualBasic.ControlChars.Cr
TextBox1.Text += myProperty.Category & Microsoft.VisualBasic.ControlChars.Cr

下面的代码示例演示如何实现一个自定义属性描述符,该描述符围绕属性提供只读包装器。 自定义 SerializeReadOnlyPropertyDescriptor 设计器中使用该属性来为控件 Size 的属性提供只读属性描述符。

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

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

        public SerializeReadOnlyPropertyDescriptor(PropertyDescriptor pd)
            : base(pd)
        {
            this._pd = pd;
        }

        public override AttributeCollection Attributes
        {
            get
            {
                return( AppendAttributeCollection(
                    this._pd.Attributes, 
                    ReadOnlyAttribute.Yes) );
            }
        }

        protected override void FillAttributes(IList attributeList)
        {
            attributeList.Add(ReadOnlyAttribute.Yes);
        }

        public override Type ComponentType
        {
            get
            {
                return this._pd.ComponentType;
            }
        }

        // The type converter for this property.
        // A translator can overwrite with its own converter.
        public override TypeConverter Converter
        {
            get
            {
                return this._pd.Converter;
            }
        }

        // Returns the property editor 
        // A translator can overwrite with its own editor.
        public override object GetEditor(Type editorBaseType)
        {
            return this._pd.GetEditor(editorBaseType);
        }

        // Specifies the property is read only.
        public override bool IsReadOnly
        {
            get
            {
                return true;
            }
        }

        public override Type PropertyType
        {
            get
            {
                return this._pd.PropertyType;
            }
        }

        public override bool CanResetValue(object component)
        {
            return this._pd.CanResetValue(component);
        }

        public override object GetValue(object component)
        {
            return this._pd.GetValue(component);
        }

        public override void ResetValue(object component)
        {
            this._pd.ResetValue(component);
        }

        public override void SetValue(object component, object val)
        {
            this._pd.SetValue(component, val);
        }

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

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

            return result;
        }

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

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

            newAttrs ??= new Attribute[0];

            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("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

以下代码示例演示如何在自定义设计器中使用 SerializeReadOnlyPropertyDescriptor

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 SerializeReadOnlyPropertyDescriptor(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.ComponentModel.Design
Imports System.Text
Imports System.Windows.Forms
Imports System.Windows.Forms.Design


<Designer(GetType(DemoControlDesigner))>  _
Public Class DemoControl
    Inherits Control
    
    Public Sub New() 
    
    End Sub
End Class

注解

属性的说明包括名称、其属性、属性关联的组件类和属性的类型。

PropertyDescriptor 提供以下属性和方法:

PropertyDescriptor 还提供以下 abstract 属性和方法:

通常,成员是通过反射实现的 abstract 。 有关反射的详细信息,请参阅 反射中的主题。

构造函数

PropertyDescriptor(MemberDescriptor)

使用指定 PropertyDescriptor 中的名称和特性初始化 MemberDescriptor 类的新实例。

PropertyDescriptor(MemberDescriptor, Attribute[])

使用指定 PropertyDescriptor 中的名称以及同时出现在 MemberDescriptorMemberDescriptor 数组中的特性初始化 Attribute 类的新实例。

PropertyDescriptor(String, Attribute[])

使用指定的名称和特性来初始化 PropertyDescriptor 类的新实例。

属性

AttributeArray

获取或设置属性的数组。

(继承自 MemberDescriptor)
Attributes

获取该成员的特性集合。

(继承自 MemberDescriptor)
Category

获取该成员所属的类别的名称,如 CategoryAttribute 中所指定的。

(继承自 MemberDescriptor)
ComponentType

当在派生类中被重写时,获取该属性绑定到的组件的类型。

Converter

获取该属性的类型转换器。

Description

获取成员的说明,如 DescriptionAttribute 中所指定的。

(继承自 MemberDescriptor)
DesignTimeOnly

获取是否只能在设计时设置该成员,如 DesignOnlyAttribute 中所指定的。

(继承自 MemberDescriptor)
DisplayName

获取可以显示在窗口(如“属性”窗口)中的名称。

(继承自 MemberDescriptor)
IsBrowsable

获取一个指示该成员是否可浏览的值,如 BrowsableAttribute 中所指定的。

(继承自 MemberDescriptor)
IsLocalizable

获取指示是否应该本地化该属性的值,如 LocalizableAttribute 中所指定的值。

IsReadOnly

当在派生类中被重写时,获取指示该属性是否为只读的值。

Name

获取此成员的名称。

(继承自 MemberDescriptor)
NameHashCode

获取此成员名称的哈希代码,如 GetHashCode() 中所指定的。

(继承自 MemberDescriptor)
PropertyType

当在派生类中被重写时,获取该属性的类型。

SerializationVisibility

获取指示是否应该序列化该属性的值,如 DesignerSerializationVisibilityAttribute 中所指定的值。

SupportsChangeEvents

获取一个值,该值指示此属性的值更改通知是否源自属性说明符的外部。

方法

AddValueChanged(Object, EventHandler)

使其他对象在此属性更改时能得到通知。

CanResetValue(Object)

当在派生类中被重写时,返回重置对象时是否更改其值。

CreateAttributeCollection()

使用传递到构造函数的特性数组创建特性的集合。

(继承自 MemberDescriptor)
CreateInstance(Type)

创建指定类型的实例。

Equals(Object)

将此对象与另一个对象进行比较,看看它们是否相等。

FillAttributes(IList)

PropertyDescriptor 的特性添加到父类中的指定特性列表中。

FillAttributes(IList)

当在派生类中被重写时,将继承类的特性添加到父类中指定的特性列表。

(继承自 MemberDescriptor)
GetChildProperties()

返回默认的 PropertyDescriptorCollection

GetChildProperties(Attribute[])

通过将指定的特性数组用作筛选器,返回 PropertyDescriptorCollection

GetChildProperties(Object)

返回给定对象的 PropertyDescriptorCollection

GetChildProperties(Object, Attribute[])

通过将指定的特性数组用作筛选器,返回给定对象的 PropertyDescriptorCollection

GetEditor(Type)

获取指定类型的编辑器。

GetHashCode()

返回此对象的哈希代码。

GetInvocationTarget(Type, Object)

此方法返回应在成员调用期间使用的对象。

GetInvocationTarget(Type, Object)

检索应在成员调用期间使用的对象。

(继承自 MemberDescriptor)
GetType()

获取当前实例的 Type

(继承自 Object)
GetTypeFromName(String)

返回使用其名称的类型。

GetValue(Object)

当在派生类中被重写时,获取组件上的属性的当前值。

GetValueChangedHandler(Object)

检索特定组件的 ValueChanged 事件处理程序的当前集合。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
OnValueChanged(Object, EventArgs)

引发已实现的 ValueChanged 事件。

RemoveValueChanged(Object, EventHandler)

使其他对象在此属性更改时能得到通知。

ResetValue(Object)

当在派生类中被重写时,将组件的此属性的值重置为默认值。

SetValue(Object, Object)

当在派生类中被重写时,将组件的值设置为一个不同的值。

ShouldSerializeValue(Object)

当在派生类中被重写时,确定一个值,该值指示是否需要永久保存此属性的值。

ToString()

返回表示当前对象的字符串。

(继承自 Object)

适用于

另请参阅