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
- Наследование
- Производный
- Атрибуты
Примеры
Следующий пример кода основан на примере в 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 предоставляет следующие свойства и методы:
Converter содержит для TypeConverter этого свойства .
IsLocalizable указывает, следует ли локализовать это свойство.
GetEditor возвращает редактор указанного типа.
PropertyDescriptor также предоставляет следующие abstract
свойства и методы:
ComponentType содержит тип компонента, к которому привязано это свойство.
IsReadOnly указывает, доступно ли это свойство только для чтения.
PropertyType получает тип свойства .
CanResetValue указывает, изменяет ли сброс компонента значение компонента.
GetValue возвращает текущее значение свойства компонента.
ResetValue сбрасывает значение этого свойства компонента.
SetValue задает для компонента другое значение.
ShouldSerializeValue указывает, нужно ли сохранять значение этого свойства.
Как правило, abstract
члены реализуются посредством отражения. Дополнительные сведения о отражении см. в разделах статьи Отражение.
Конструкторы
PropertyDescriptor(MemberDescriptor) |
Инициализирует новый экземпляр класса PropertyDescriptor, используя имя и атрибуты заданного объекта MemberDescriptor. |
PropertyDescriptor(MemberDescriptor, Attribute[]) |
Инициализирует новый экземпляр класса PropertyDescriptor, используя имя в заданном дескрипторе MemberDescriptor и атрибуты как в дескрипторе MemberDescriptor, так и в массиве 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) |
Извлекает текущий набор обработчиков |
MemberwiseClone() |
Создает неполную копию текущего объекта Object. (Унаследовано от Object) |
OnValueChanged(Object, EventArgs) |
Вызывает реализованное |
RemoveValueChanged(Object, EventHandler) |
Позволяет уведомить другие объекты об изменении этого свойства. |
ResetValue(Object) |
В случае переопределения в производном классе, сбрасывает значение для этого свойства компонента в значение по умолчанию. |
SetValue(Object, Object) |
При переопределении в производном классе устанавливает другое значение для компонента. |
ShouldSerializeValue(Object) |
При переопределении в производном классе определяет значение, показывающее, нужно ли сохранить данное значение свойства. |
ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |