Бөлісу құралы:


TypeDescriptor.GetProperties Метод

Определение

Возвращает коллекцию свойств компонента или типа.

Перегрузки

Имя Описание
GetProperties(Object)

Возвращает коллекцию свойств для указанного компонента.

GetProperties(Type)

Возвращает коллекцию свойств для указанного типа компонента.

GetProperties(Object, Attribute[])

Возвращает коллекцию свойств для указанного компонента, используя указанный массив атрибутов в качестве фильтра.

GetProperties(Object, Boolean)

Возвращает коллекцию свойств для указанного компонента с помощью дескриптора типа по умолчанию.

GetProperties(Type, Attribute[])

Возвращает коллекцию свойств для указанного типа компонента, используя указанный массив атрибутов в качестве фильтра.

GetProperties(Object, Attribute[], Boolean)

Возвращает коллекцию свойств для указанного компонента, используя указанный массив атрибутов в качестве фильтра и используя дескриптор пользовательского типа.

GetProperties(Object)

Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs

Возвращает коллекцию свойств для указанного компонента.

public:
 static System::ComponentModel::PropertyDescriptorCollection ^ GetProperties(System::Object ^ component);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The Type of component cannot be statically discovered.")]
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(object component);
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(object component);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The Type of component cannot be statically discovered.")>]
static member GetProperties : obj -> System.ComponentModel.PropertyDescriptorCollection
static member GetProperties : obj -> System.ComponentModel.PropertyDescriptorCollection
Public Shared Function GetProperties (component As Object) As PropertyDescriptorCollection

Параметры

component
Object

Компонент, для получения свойств для.

Возвращаемое значение

А PropertyDescriptorCollection со свойствами для указанного компонента.

Атрибуты

Исключения

component — это межпроцессный удаленный объект.

Примеры

В следующем примере кода демонстрируется использование GetProperties метода для доступа к свойствам элемента управления. Этот пример кода является частью более крупного примера, предоставленного для ComponentDesigner класса.

// This is the shadowed property on the designer.
// This value will be serialized instead of the 
// value of the control's property.
public Color BackColor
{
    get => (Color)ShadowProperties[nameof(BackColor)];
    set
    {
        if (changeService != null)
        {
            PropertyDescriptor backColorDesc =
                TypeDescriptor.GetProperties(Control)["BackColor"];

            changeService.OnComponentChanging(
                Control,
                backColorDesc);

            ShadowProperties[nameof(BackColor)] = value;

            changeService.OnComponentChanged(
                Control,
                backColorDesc,
                null,
                null);
        }
    }
}
' This is the shadowed property on the designer.
' This value will be serialized instead of the 
' value of the control's property.

Public Property BackColor() As Color
    Get
        Return CType(ShadowProperties("BackColor"), Color)
    End Get
    Set(ByVal value As Color)
        If (Me.changeService IsNot Nothing) Then
            Dim backColorDesc As PropertyDescriptor = TypeDescriptor.GetProperties(Me.Control)("BackColor")

            Me.changeService.OnComponentChanging(Me.Control, backColorDesc)

            Me.ShadowProperties("BackColor") = value

            Me.changeService.OnComponentChanged(Me.Control, backColorDesc, Nothing, Nothing)
        End If
    End Set
End Property

Комментарии

Свойства компонента могут отличаться от свойств класса, так как сайт может добавлять или удалять свойства, если компонент находится на сайте.

component Если параметр имеет значениеnull, возвращается пустая коллекция.

Порядок возвращаемой коллекции не гарантируется идентичным между вызовами, поэтому всегда упорядочивать его перед использованием.

См. также раздел

Применяется к

GetProperties(Type)

Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs

Возвращает коллекцию свойств для указанного типа компонента.

public:
 static System::ComponentModel::PropertyDescriptorCollection ^ GetProperties(Type ^ componentType);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered.")]
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(Type componentType);
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(Type componentType);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered.")>]
static member GetProperties : Type -> System.ComponentModel.PropertyDescriptorCollection
static member GetProperties : Type -> System.ComponentModel.PropertyDescriptorCollection
Public Shared Function GetProperties (componentType As Type) As PropertyDescriptorCollection

Параметры

componentType
Type

Объект, Type представляющий компонент для получения свойств.

Возвращаемое значение

Со PropertyDescriptorCollection свойствами для указанного типа компонента.

Атрибуты

Комментарии

Вызовите эту версию этого метода, только если у вас нет экземпляра объекта.

componentType Если параметр имеет значениеnull, возвращается пустая коллекция.

Порядок возвращаемой коллекции не гарантируется идентичным между вызовами, поэтому всегда упорядочивать его перед использованием.

См. также раздел

Применяется к

GetProperties(Object, Attribute[])

Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs

Возвращает коллекцию свойств для указанного компонента, используя указанный массив атрибутов в качестве фильтра.

public:
 static System::ComponentModel::PropertyDescriptorCollection ^ GetProperties(System::Object ^ component, cli::array <Attribute ^> ^ attributes);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The Type of component cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")]
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, Attribute[]? attributes);
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, Attribute[] attributes);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The Type of component cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")>]
static member GetProperties : obj * Attribute[] -> System.ComponentModel.PropertyDescriptorCollection
static member GetProperties : obj * Attribute[] -> System.ComponentModel.PropertyDescriptorCollection
Public Shared Function GetProperties (component As Object, attributes As Attribute()) As PropertyDescriptorCollection

Параметры

component
Object

Компонент, для получения свойств для.

attributes
Attribute[]

Массив типа Attribute , используемый в качестве фильтра.

Возвращаемое значение

Со PropertyDescriptorCollection свойствами, которые соответствуют указанным атрибутам указанного компонента.

Атрибуты

Исключения

component — это межпроцессный удаленный объект.

Примеры

В следующем примере кода показано, как реализовать GetProperties метод. Этот пример кода является частью более крупного примера, предоставленного для PropertyTab класса.

// Returns the properties of the specified component extended with
// a CategoryAttribute reflecting the name of the type of the property.
[ReflectionPermission(SecurityAction::Demand, Flags=ReflectionPermissionFlag::MemberAccess)]
virtual System::ComponentModel::PropertyDescriptorCollection^ GetProperties( Object^ component, array<System::Attribute^>^attributes ) override
{
   PropertyDescriptorCollection^ props;
   if ( attributes == nullptr )
            props = TypeDescriptor::GetProperties( component );
   else
            props = TypeDescriptor::GetProperties( component, attributes );

   array<PropertyDescriptor^>^propArray = gcnew array<PropertyDescriptor^>(props->Count);
   for ( int i = 0; i < props->Count; i++ )
   {
      // Create a new PropertyDescriptor from the old one, with
      // a CategoryAttribute matching the name of the type.
      array<Attribute^>^temp0 = {gcnew CategoryAttribute( props[ i ]->PropertyType->Name )};
      propArray[ i ] = TypeDescriptor::CreateProperty( props[ i ]->ComponentType, props[ i ], temp0 );

   }
   return gcnew PropertyDescriptorCollection( propArray );
}

virtual System::ComponentModel::PropertyDescriptorCollection^ GetProperties( Object^ component ) override
{
   return this->GetProperties( component, nullptr );
}
// Returns the properties of the specified component extended with 
// a CategoryAttribute reflecting the name of the type of the property.
public override PropertyDescriptorCollection GetProperties(object component, System.Attribute[] attributes)
{
    PropertyDescriptorCollection props = attributes == null ? TypeDescriptor.GetProperties(component) : TypeDescriptor.GetProperties(component, attributes);
    PropertyDescriptor[] propArray = new PropertyDescriptor[props.Count];
    for (int i = 0; i < props.Count; i++)
    {
        // Create a new PropertyDescriptor from the old one, with 
        // a CategoryAttribute matching the name of the type.
        propArray[i] = TypeDescriptor.CreateProperty(props[i].ComponentType, props[i], new CategoryAttribute(props[i].PropertyType.Name));
    }
    return new PropertyDescriptorCollection(propArray);
}

public override PropertyDescriptorCollection GetProperties(object component) => GetProperties(component, null);

Комментарии

Свойства параметра component могут отличаться от свойств класса, так как сайт может добавлять или удалять свойства, если component параметр находится на сайте.

Массив attributes параметров используется для фильтрации массива. Фильтрация определяется следующими правилами:

  • Если свойство не имеет Attribute одного класса, свойство не входит в возвращаемый массив.

  • Если атрибут является экземпляром Attribute класса, свойство должно быть точным совпадением или оно не входит в возвращаемый массив.

  • Attribute Если экземпляр указан и является свойством по умолчанию, он включается в возвращаемый массив, даже если в свойстве нет экземпляраAttribute.

  • Если attributes атрибут по умолчанию, метод соответствует регистру, GetProperties если свойство не имеет примененного атрибута.

В противном component случае nullвозвращается пустая коллекция.

Порядок возвращаемой коллекции не гарантируется идентичным между вызовами, поэтому всегда упорядочивать его перед использованием.

См. также раздел

Применяется к

GetProperties(Object, Boolean)

Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs

Возвращает коллекцию свойств для указанного компонента с помощью дескриптора типа по умолчанию.

public:
 static System::ComponentModel::PropertyDescriptorCollection ^ GetProperties(System::Object ^ component, bool noCustomTypeDesc);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The Type of component cannot be statically discovered.")]
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, bool noCustomTypeDesc);
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, bool noCustomTypeDesc);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The Type of component cannot be statically discovered.")>]
static member GetProperties : obj * bool -> System.ComponentModel.PropertyDescriptorCollection
static member GetProperties : obj * bool -> System.ComponentModel.PropertyDescriptorCollection
Public Shared Function GetProperties (component As Object, noCustomTypeDesc As Boolean) As PropertyDescriptorCollection

Параметры

component
Object

Компонент, для получения свойств для.

noCustomTypeDesc
Boolean

true не учитывать сведения о описании пользовательского типа; falseв противном случае .

Возвращаемое значение

А PropertyDescriptorCollection со свойствами для указанного компонента.

Атрибуты

Исключения

component — это межпроцессный удаленный объект.

Комментарии

Свойства параметра component могут отличаться от свойств класса, так как сайт может добавлять или удалять свойства, если component параметр находится на сайте.

В противном component случае nullвозвращается пустая коллекция.

Порядок возвращаемой коллекции не гарантируется идентичным между вызовами, поэтому всегда упорядочивать его перед использованием.

См. также раздел

Применяется к

GetProperties(Type, Attribute[])

Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs

Возвращает коллекцию свойств для указанного типа компонента, используя указанный массив атрибутов в качестве фильтра.

public:
 static System::ComponentModel::PropertyDescriptorCollection ^ GetProperties(Type ^ componentType, cli::array <Attribute ^> ^ attributes);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")]
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(Type componentType, Attribute[]? attributes);
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(Type componentType, Attribute[] attributes);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")>]
static member GetProperties : Type * Attribute[] -> System.ComponentModel.PropertyDescriptorCollection
static member GetProperties : Type * Attribute[] -> System.ComponentModel.PropertyDescriptorCollection
Public Shared Function GetProperties (componentType As Type, attributes As Attribute()) As PropertyDescriptorCollection

Параметры

componentType
Type

Целевой Type компонент.

attributes
Attribute[]

Массив типа Attribute , используемый в качестве фильтра.

Возвращаемое значение

Со PropertyDescriptorCollection свойствами, которые соответствуют указанным атрибутам этого типа компонента.

Атрибуты

Примеры

В следующем примере кода показано, как реализовать GetProperties метод. Этот пример кода является частью более крупного примера, предоставленного для PropertyTab класса.

// Returns the properties of the specified component extended with
// a CategoryAttribute reflecting the name of the type of the property.
[ReflectionPermission(SecurityAction::Demand, Flags=ReflectionPermissionFlag::MemberAccess)]
virtual System::ComponentModel::PropertyDescriptorCollection^ GetProperties( Object^ component, array<System::Attribute^>^attributes ) override
{
   PropertyDescriptorCollection^ props;
   if ( attributes == nullptr )
            props = TypeDescriptor::GetProperties( component );
   else
            props = TypeDescriptor::GetProperties( component, attributes );

   array<PropertyDescriptor^>^propArray = gcnew array<PropertyDescriptor^>(props->Count);
   for ( int i = 0; i < props->Count; i++ )
   {
      // Create a new PropertyDescriptor from the old one, with
      // a CategoryAttribute matching the name of the type.
      array<Attribute^>^temp0 = {gcnew CategoryAttribute( props[ i ]->PropertyType->Name )};
      propArray[ i ] = TypeDescriptor::CreateProperty( props[ i ]->ComponentType, props[ i ], temp0 );

   }
   return gcnew PropertyDescriptorCollection( propArray );
}

virtual System::ComponentModel::PropertyDescriptorCollection^ GetProperties( Object^ component ) override
{
   return this->GetProperties( component, nullptr );
}
// Returns the properties of the specified component extended with 
// a CategoryAttribute reflecting the name of the type of the property.
public override PropertyDescriptorCollection GetProperties(object component, System.Attribute[] attributes)
{
    PropertyDescriptorCollection props = attributes == null ? TypeDescriptor.GetProperties(component) : TypeDescriptor.GetProperties(component, attributes);
    PropertyDescriptor[] propArray = new PropertyDescriptor[props.Count];
    for (int i = 0; i < props.Count; i++)
    {
        // Create a new PropertyDescriptor from the old one, with 
        // a CategoryAttribute matching the name of the type.
        propArray[i] = TypeDescriptor.CreateProperty(props[i].ComponentType, props[i], new CategoryAttribute(props[i].PropertyType.Name));
    }
    return new PropertyDescriptorCollection(propArray);
}

public override PropertyDescriptorCollection GetProperties(object component) => GetProperties(component, null);

Комментарии

Вызовите эту версию этого метода, только если у вас нет экземпляра объекта.

Массив attributes параметров используется для фильтрации массива. Фильтрация определяется следующими правилами:

  • Если свойство не имеет Attribute одного класса, свойство не входит в возвращаемый массив.

  • Если атрибут является экземпляром Attribute класса, свойство должно быть точным совпадением или оно не входит в возвращаемый массив.

  • Attribute Если экземпляр указан и является свойством по умолчанию, он включается в возвращаемый массив, даже если в свойстве нет экземпляраAttribute.

  • Если attributes атрибут по умолчанию, метод соответствует регистру, GetProperties если свойство не имеет примененного атрибута.

componentType Если параметр имеет значениеnull, возвращается пустая коллекция.

Порядок возвращаемой коллекции не гарантируется идентичным между вызовами, поэтому всегда упорядочивать его перед использованием.

См. также раздел

Применяется к

GetProperties(Object, Attribute[], Boolean)

Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs
Исходный код:
TypeDescriptor.cs

Возвращает коллекцию свойств для указанного компонента, используя указанный массив атрибутов в качестве фильтра и используя дескриптор пользовательского типа.

public:
 static System::ComponentModel::PropertyDescriptorCollection ^ GetProperties(System::Object ^ component, cli::array <Attribute ^> ^ attributes, bool noCustomTypeDesc);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The Type of component cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")]
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, Attribute[]? attributes, bool noCustomTypeDesc);
public static System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, Attribute[] attributes, bool noCustomTypeDesc);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The Type of component cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")>]
static member GetProperties : obj * Attribute[] * bool -> System.ComponentModel.PropertyDescriptorCollection
static member GetProperties : obj * Attribute[] * bool -> System.ComponentModel.PropertyDescriptorCollection
Public Shared Function GetProperties (component As Object, attributes As Attribute(), noCustomTypeDesc As Boolean) As PropertyDescriptorCollection

Параметры

component
Object

Компонент, для получения свойств для.

attributes
Attribute[]

Массив типа Attribute , используемый в качестве фильтра.

noCustomTypeDesc
Boolean

true не учитывать сведения о описании пользовательского типа; falseв противном случае .

Возвращаемое значение

С PropertyDescriptorCollection событиями, которые соответствуют указанным атрибутам указанного компонента.

Атрибуты

Исключения

component — это межпроцессный удаленный объект.

Комментарии

Свойства для component класса могут отличаться от свойств класса, так как сайт может добавлять или удалять свойства, если он находится на component сайте.

Массив attributes параметров используется для фильтрации массива. Фильтрация определяется следующими правилами:

  • Если свойство не имеет Attribute одного класса, свойство не входит в возвращаемый массив.

  • Если атрибут является экземпляром Attribute класса, свойство должно быть точным совпадением или оно не входит в возвращаемый массив.

  • Attribute Если экземпляр указан и является свойством по умолчанию, он включается в возвращаемый массив, даже если в свойстве нет экземпляраAttribute.

  • Если attributes атрибут по умолчанию, метод соответствует регистру, GetProperties если свойство не имеет примененного атрибута.

component Если параметр имеет значениеnull, возвращается пустая коллекция.

Порядок возвращаемой коллекции не гарантируется идентичным между вызовами, поэтому всегда упорядочивать его перед использованием.

См. также раздел

Применяется к