Type.GetProperties Metoda

Definicja

Pobiera właściwości bieżącego Typeelementu .

Przeciążenia

GetProperties()

Zwraca wszystkie właściwości publiczne bieżącego Typeelementu .

GetProperties(BindingFlags)

Po przesłonięciu w klasie pochodnej wyszukuje właściwości bieżącego Typeelementu , używając określonych ograniczeń powiązania.

GetProperties()

Źródło:
Type.cs
Źródło:
Type.cs
Źródło:
Type.cs

Zwraca wszystkie właściwości publiczne bieżącego Typeelementu .

public:
 cli::array <System::Reflection::PropertyInfo ^> ^ GetProperties();
public:
 virtual cli::array <System::Reflection::PropertyInfo ^> ^ GetProperties();
public System.Reflection.PropertyInfo[] GetProperties ();
member this.GetProperties : unit -> System.Reflection.PropertyInfo[]
abstract member GetProperties : unit -> System.Reflection.PropertyInfo[]
override this.GetProperties : unit -> System.Reflection.PropertyInfo[]
Public Function GetProperties () As PropertyInfo()

Zwraca

Tablica PropertyInfo obiektów reprezentujących wszystkie właściwości publiczne bieżącego Typeobiektu .

-lub-

Pusta tablica typu PropertyInfo, jeśli bieżący Type nie ma właściwości publicznych.

Implementuje

Przykłady

W poniższym przykładzie pokazano użycie GetProperties metody .

array<PropertyInfo^>^myPropertyInfo;

// Get the properties of 'Type' class object.
myPropertyInfo = Type::GetType( "System.Type" )->GetProperties();
Console::WriteLine( "Properties of System.Type are:" );
for ( int i = 0; i < myPropertyInfo->Length; i++ )
{
   Console::WriteLine( myPropertyInfo[ i ] );

}
PropertyInfo[] myPropertyInfo;
// Get the properties of 'Type' class object.
myPropertyInfo = Type.GetType("System.Type").GetProperties();
Console.WriteLine("Properties of System.Type are:");
for (int i = 0; i < myPropertyInfo.Length; i++)
{
    Console.WriteLine(myPropertyInfo[i].ToString());
}
// Get the properties of 'Type' class object.
let myPropertyInfo = Type.GetType("System.Type").GetProperties()
printfn "Properties of System.Type are:"
for pi in myPropertyInfo do
    printfn $"{pi}"
Dim myPropertyInfo() As PropertyInfo
' Get the properties of 'Type' class object.
myPropertyInfo = Type.GetType("System.Type").GetProperties()
Console.WriteLine("Properties of System.Type are:")
Dim i As Integer
For i = 0 To myPropertyInfo.Length - 1
   Console.WriteLine(myPropertyInfo(i).ToString())
Next i

Uwagi

Wywołanie tego przeciążenia jest równoważne wywołaniu GetProperties(BindingFlags) przeciążenia z argumentem równym bindingAttrBindingFlags.Instance | BindingFlags.Static | BindingFlags.Public w języku C# i BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public w Visual Basic. Zwraca wszystkie wystąpienia publiczne i właściwości statyczne, zarówno te zdefiniowane przez typ reprezentowany przez bieżący Type obiekt, jak i te dziedziczone z jego typów bazowych.

Właściwość jest uważana za publiczne odbicie, jeżeli ma co najmniej jeden publiczny akcesor. W przeciwnym razie właściwość jest uznawana za prywatną i należy jej użyć BindingFlags.NonPublic | | BindingFlags.InstanceBindingFlags.Static (w visual basic połącz wartości przy użyciu metody Or), aby ją pobrać.

W przypadku platformy .NET 6 i starszych wersji GetProperties metoda nie zwraca właściwości w określonej kolejności, takiej jak alfabetyczne lub kolejność deklaracji. Kod nie może zależeć od kolejności zwracanej właściwości, ponieważ ta kolejność różni się. Jednak począwszy od platformy .NET 7 kolejność jest deterministyczna na podstawie kolejności metadanych w zestawie.

W poniższej tabeli przedstawiono, które elementy członkowskie klasy bazowej są zwracane przez Get metody podczas odzwierciedlania typu.

Typ elementu członkowskiego Static Niestatyczna
Konstruktor Nie Nie
Pole Nie Tak. Pole jest zawsze ukryte przez nazwę i podpis.
Zdarzenie Nie dotyczy Zasadą systemu typu jest to, że dziedziczenie jest takie samo, jak w przypadku metod, które implementują właściwość. Odbicie traktuje właściwości jako ukryte przez nazwę i podpis. Patrz Uwaga 2 poniżej.
Metoda Nie Tak. Metodą (zarówno wirtualną, jak i niewirtualną) może być ukrycie przez nazwę lub przez nazwę i podpis.
Typu zagnieżdżony Nie Nie
Właściwość Nie dotyczy Zasadą systemu typu jest to, że dziedziczenie jest takie samo, jak w przypadku metod, które implementują właściwość. Odbicie traktuje właściwości jako ukryte przez nazwę i podpis. Patrz Uwaga 2 poniżej.
  1. Ukrycie przez nazwę i podpis dotyczy wszystkich części podpisu, w tym modyfikatorów niestandardowych, zwraca typy, typy parametrów, wartowników i niezarządzane konwencje wywoływania. To jest porównanie binarne.

  2. W celu odbicia właściwości i zdarzenia są ukrywane przez nazwę i podpis. Jeśli istnieje właściwość z akcesorem pobierania i ustawiania w klasie bazowej, ale odziedziczona klasa ma tylko akcesor pobierania, właściwość klasy odziedziczonej ukrywa właściwości klasy bazowej, a nie można uzyskać dostępu do metody ustawiającej w klasie bazowej.

  3. Atrybuty niestandardowe nie są częścią wspólnego typu systemowego.

Jeśli bieżący Type reprezentuje skonstruowany typ ogólny, ta metoda zwraca PropertyInfo obiekty z parametrami typu zastąpionymi przez odpowiednie argumenty typu.

Jeśli bieżący Type reprezentuje parametr typu w definicji typu ogólnego lub metody ogólnej, ta metoda wyszukuje właściwości ograniczenia klasy.

Zobacz też

Dotyczy

GetProperties(BindingFlags)

Źródło:
Type.cs
Źródło:
Type.cs
Źródło:
Type.cs

Po przesłonięciu w klasie pochodnej wyszukuje właściwości bieżącego Typeelementu , używając określonych ograniczeń powiązania.

public:
 abstract cli::array <System::Reflection::PropertyInfo ^> ^ GetProperties(System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr);
abstract member GetProperties : System.Reflection.BindingFlags -> System.Reflection.PropertyInfo[]
Public MustOverride Function GetProperties (bindingAttr As BindingFlags) As PropertyInfo()

Parametry

bindingAttr
BindingFlags

Bitowa kombinacja wartości wyliczenia, które określają sposób przeprowadzania wyszukiwania.

-lub-

Default aby zwrócić pustą tablicę.

Zwraca

Tablica obiektów reprezentujących wszystkie właściwości bieżącego Type , które są zgodne z określonymi ograniczeniami powiązania.

-lub-

Pusta tablica typu PropertyInfo, jeśli bieżący Type nie ma właściwości, lub jeśli żadna z właściwości nie jest zgodna z ograniczeniami powiązania.

Implementuje

Przykłady

W poniższym przykładzie zdefiniowano klasę o nazwie PropertyClass zawierającą sześć właściwości: dwie są publiczne, jedna jest prywatna, jedna jest chroniona wewnętrznie ( w Visual Basic), a jedna jest chroniona wewnętrznie (FriendProtected Friendw Visual Basic). Następnie wyświetla niektóre podstawowe informacje o właściwościach (nazwa i typ właściwości, czy jest on odczytywany/zapisywany, oraz widoczność jej get i set metod dostępu) dla właściwości, które są zgodne z określonymi ograniczeniami powiązania.

using namespace System;
using namespace System::Reflection;

// Create a class having three properties.
public ref class PropertyClass
{

public:
   property String^ Property1
   {
      String^ get()
      {
         return "hello";
      }
   }

   property String^ Property2 
   {
      String^ get()
      {
         return "hello";
      }
   }

protected:
   property String^ Property3
   {
      String^ get()
      {
         return "hello";
      }
   }

private:
   property int Property4
   {
      int get()
      {
         return 32;
      }
   }

internal:
   property String^ Property5
   {
      String^ get()
      {
         return "value";
      }
   }
   
public protected:
   property String^ Property6
   {
      String^ get()
      {
         return "value";
      }
   }
};

String^ GetVisibility(MethodInfo^ accessor)
{
    if (accessor->IsPublic)
       return "Public";
    else if (accessor->IsPrivate)
       return "Private";
    else if (accessor->IsFamily)
       return "Protected";
    else if (accessor->IsAssembly)
       return "Internal/Friend";
    else
       return "Protected Internal/Friend";
}

void DisplayPropertyInfo(array<PropertyInfo^>^ propInfos )
{
   // Display information for all properties.
   for each(PropertyInfo^ propInfo in propInfos) {
      bool readable = propInfo->CanRead;
      bool writable = propInfo->CanWrite;
      
      Console::WriteLine("   Property name: {0}", propInfo->Name);
      Console::WriteLine("   Property type: {0}", propInfo->PropertyType);
      Console::WriteLine("   Read-Write:    {0}", readable && writable);
      if (readable) {
         MethodInfo^ getAccessor = propInfo->GetMethod;
         Console::WriteLine("   Visibility:    {0}",
                           GetVisibility(getAccessor));
      }
      if (writable) {
         MethodInfo^ setAccessor = propInfo->SetMethod;
         Console::WriteLine("   Visibility:    {0}",
                            GetVisibility(setAccessor));
      }
      Console::WriteLine();
   }
}

void main()
{
   Type^ myType = PropertyClass::typeid;
   
   // Get the public properties.
   array<PropertyInfo^>^propInfos = myType->GetProperties( static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
   Console::WriteLine("The number of public properties: {0}.\n",
                      propInfos->Length);
   // Display the public properties.
   DisplayPropertyInfo( propInfos );
   
   // Get the non-public properties.
   array<PropertyInfo^>^propInfos1 = myType->GetProperties( static_cast<BindingFlags>(BindingFlags::NonPublic | BindingFlags::Instance) );
   Console::WriteLine("The number of non-public properties: {0}.\n",
                      propInfos1->Length);
   // Display all the non-public properties.
   DisplayPropertyInfo(propInfos1);
}
// The example displays the following output:
//       The number of public properties: 2.
//
//          Property name: Property2
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Public
//
//          Property name: Property1
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Public
//
//       The number of non-public properties: 4.
//
//          Property name: Property6
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Protected Internal/Friend
//
//          Property name: Property5
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Internal/Friend
//
//          Property name: Property4
//          Property type: System.Int32
//          Read-Write:    False
//          Visibility:    Private
//
//          Property name: Property3
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Protected
using System;
using System.Reflection;

// Create a class having six properties.
public class PropertyClass
{
    public String Property1
    {
        get { return "hello"; }
    }

    public String Property2
    {
        get { return "hello"; }
    }

    protected String Property3
    {
        get { return "hello"; }
    }

    private Int32 Property4
    {
        get { return 32; }
    }

    internal String Property5
    {
       get { return "value"; }
    }

    protected internal String Property6
    {
       get { return "value"; }
    }
}

public class Example
{
    public static void Main()
    {
        Type t = typeof(PropertyClass);
        // Get the public properties.
        PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public|BindingFlags.Instance);
        Console.WriteLine("The number of public properties: {0}.\n",
                          propInfos.Length);
        // Display the public properties.
        DisplayPropertyInfo(propInfos);

        // Get the nonpublic properties.
        PropertyInfo[] propInfos1 = t.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance);
        Console.WriteLine("The number of non-public properties: {0}.\n",
                          propInfos1.Length);
        // Display all the nonpublic properties.
        DisplayPropertyInfo(propInfos1);
    }

    public static void DisplayPropertyInfo(PropertyInfo[] propInfos)
    {
        // Display information for all properties.
        foreach (var propInfo in propInfos) {
            bool readable = propInfo.CanRead;
            bool writable = propInfo.CanWrite;

            Console.WriteLine("   Property name: {0}", propInfo.Name);
            Console.WriteLine("   Property type: {0}", propInfo.PropertyType);
            Console.WriteLine("   Read-Write:    {0}", readable & writable);
            if (readable) {
               MethodInfo getAccessor = propInfo.GetMethod;
               Console.WriteLine("   Visibility:    {0}",
                                 GetVisibility(getAccessor));
            }
            if (writable) {
               MethodInfo setAccessor = propInfo.SetMethod;
               Console.WriteLine("   Visibility:    {0}",
                                 GetVisibility(setAccessor));
            }
            Console.WriteLine();
        }
    }

    public static String GetVisibility(MethodInfo accessor)
    {
       if (accessor.IsPublic)
          return "Public";
       else if (accessor.IsPrivate)
          return "Private";
       else if (accessor.IsFamily)
          return "Protected";
       else if (accessor.IsAssembly)
          return "Internal/Friend";
       else
          return "Protected Internal/Friend";
    }
}
// The example displays the following output:
//       The number of public properties: 2.
//
//          Property name: Property1
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Public
//
//          Property name: Property2
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Public
//
//       The number of non-public properties: 4.
//
//          Property name: Property3
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Protected
//
//          Property name: Property4
//          Property type: System.Int32
//          Read-Write:    False
//          Visibility:    Private
//
//          Property name: Property5
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Internal/Friend
//
//          Property name: Property6
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Protected Internal/Friend
open System.Reflection

// Create a class having four properties.
type PropertyClass() =
    member _.Property1 = 
        "hello"

    member _.Property2 = 
        "hello"

    member private _.Property3 = 
        32

    member internal _.Property4 =
       "value"

let getVisibility (accessor: MethodInfo) =
    if accessor.IsPublic then
        "Public"
    elif accessor.IsPrivate then
        "Private"
    elif accessor.IsFamily then
        "Protected"
    elif accessor.IsAssembly then
        "Internal/Friend"
    else
        "Protected Internal/Friend"

let displayPropertyInfo (propInfos: #seq<PropertyInfo>) = 
    // Display information for all properties.
    for propInfo in propInfos do
        let readable = propInfo.CanRead
        let writable = propInfo.CanWrite

        printfn $"   Property name: {propInfo.Name}"
        printfn $"   Property type: {propInfo.PropertyType}"
        printfn $"   Read-Write:    {readable && writable}"
        if readable then
            let getAccessor = propInfo.GetMethod
            printfn $"   Visibility:    {getVisibility getAccessor}"
        if writable then
            let setAccessor = propInfo.SetMethod
            printfn $"   Visibility:    {getVisibility setAccessor}"
        printfn ""

let t = typeof<PropertyClass>
// Get the public properties.
let propInfos = t.GetProperties(BindingFlags.Public ||| BindingFlags.Instance)
printfn $"The number of public properties: {propInfos.Length}.\n"
// Display the public properties.
displayPropertyInfo propInfos

// Get the nonpublic properties.
let propInfos1 = t.GetProperties(BindingFlags.NonPublic ||| BindingFlags.Instance)
printfn $"The number of non-public properties: {propInfos1.Length}.\n"
// Display all the nonpublic properties.
displayPropertyInfo propInfos1

// The example displays the following output:
//       The number of public properties: 2.
//
//          Property name: Property1
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Public
//
//          Property name: Property2
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Public
//
//       The number of non-public properties: 2.
//
//          Property name: Property3
//          Property type: System.Int32
//          Read-Write:    False
//          Visibility:    Private
//
//          Property name: Property4
//          Property type: System.String
//          Read-Write:    False
//          Visibility:    Internal/Friend
Imports System.Reflection

' Create a class having six properties.
Public Class PropertyClass
    Public ReadOnly Property Property1() As String
        Get
            Return "hello"
        End Get
    End Property

    Public ReadOnly Property Property2() As String
        Get
            Return "hello"
        End Get
    End Property

    Protected ReadOnly Property Property3() As String
        Get
            Return "hello"
        End Get
    End Property

    Private ReadOnly Property Property4 As Integer
        Get
           Return 32
        End Get
    End Property

    Friend ReadOnly Property Property5 As String
       Get
          Return "value"
       End Get
    End Property

    Protected Friend ReadOnly Property Property6 As String
       Get
          Return "value"
       End Get
    End Property
End Class

Public Module Example
    Public Sub Main()
        Dim t As Type = GetType(PropertyClass)
        ' Get the public properties.
        Dim propInfos As PropertyInfo() = t.GetProperties(BindingFlags.Public Or BindingFlags.Instance)
        Console.WriteLine("The number of public properties: {0}",
                          propInfos.Length)
        Console.WriteLine()
        ' Display the public properties.
        DisplayPropertyInfo(propInfos)

        ' Get the non-public properties.
        Dim propInfos1 As PropertyInfo() = t.GetProperties(BindingFlags.NonPublic Or BindingFlags.Instance)
        Console.WriteLine("The number of non-public properties: {0}",
                          propInfos1.Length)
        Console.WriteLine()
        ' Display all the non-public properties.
        DisplayPropertyInfo(propInfos1)
    End Sub

    Public Sub DisplayPropertyInfo(ByVal propInfos() As PropertyInfo)
        ' Display information for all properties.
        For Each propInfo In propInfos
            Dim readable As Boolean = propInfo.CanRead
            Dim writable As Boolean = propInfo.CanWrite
            
            Console.WriteLine("   Property name: {0}", propInfo.Name)
            Console.WriteLine("   Property type: {0}", propInfo.PropertyType)
            Console.WriteLine("   Read-Write:    {0}", readable And writable)
            If readable Then
               Dim getAccessor As MethodInfo = propInfo.GetMethod
               Console.WriteLine("   Visibility:    {0}",
                                 GetVisibility(getAccessor))
            End If
            If writable Then
               Dim setAccessor As MethodInfo = propInfo.SetMethod
               Console.WriteLine("   Visibility:    {0}",
                                 GetVisibility(setAccessor))
            End If
            Console.WriteLine()
        Next
    End Sub
    
    Public Function GetVisibility(accessor As MethodInfo) As String
       If accessor.IsPublic Then
          Return "Public"
       ElseIf accessor.IsPrivate Then
          Return "Private"
       Else If accessor.IsFamily Then
          Return "Protected"
       Else If accessor.IsAssembly Then
          Return "Internal/Friend"
       Else
          Return "Protected Internal/Friend"
       End If
    End Function
End Module
' The example displays the following output:
'       The number of public properties: 2
'
'          Property name: Property1
'          Property type: System.String
'          Read-Write:    False
'          Visibility:    Public
'
'          Property name: Property2
'          Property type: System.String
'          Read-Write:    False
'          Visibility:    Public
'
'       The number of non-public properties: 4
'
'          Property name: Property3
'          Property type: System.String
'          Read-Write:    False
'          Visibility:    Protected
'
'          Property name: Property4
'          Property type: System.Int32
'          Read-Write:    False
'          Visibility:    Private
'
'          Property name: Property5
'          Property type: System.String
'          Read-Write:    False
'          Visibility:    Internal/Friend
'
'          Property name: Property6
'          Property type: System.String
'          Read-Write:    False
'          Visibility:    Protected Internal/Friend

Uwagi

GetProperties(BindingFlags) Aby przeciążenie pomyślnie pobrało informacje o właściwości, bindingAttr argument musi zawierać co najmniej jedną z elementów i , a także co najmniej jedną BindingFlags.NonPublicBindingFlags.Instance z wartości i BindingFlags.StaticBindingFlags.Public.

Następujące BindingFlags flagi filtru mogą służyć do definiowania właściwości do uwzględnienia w wyszukiwaniu:

  • Określ BindingFlags.Instance , aby uwzględnić metody wystąpienia.

  • Określ BindingFlags.Static , aby uwzględnić metody statyczne.

  • Określ BindingFlags.Public , aby uwzględnić właściwości publiczne w wyszukiwaniu. Właściwość jest uważana za publiczne odbicie, jeżeli ma co najmniej jeden publiczny akcesor.

  • Określ BindingFlags.NonPublic , aby uwzględnić właściwości inne niż publiczne (czyli prywatne, wewnętrzne i chronione) w wyszukiwaniu. Zwracane są tylko właściwości chronione i wewnętrzne w klasach bazowych; właściwości prywatne w klasach bazowych nie są zwracane.

  • Określ BindingFlags.FlattenHierarchy , aby uwzględnić public i protected statyczne elementy członkowskie w hierarchii; private składowe statyczne w odziedziczonych klasach nie są uwzględniane.

  • Określ BindingFlags.Default sam, aby zwrócić pustą PropertyInfo tablicę.

Następujące BindingFlags flagi modyfikatora mogą służyć do zmiany sposobu działania wyszukiwania:

  • BindingFlags.DeclaredOnly aby wyszukać tylko właściwości zadeklarowane w Typeobiekcie , a nie właściwości, które zostały po prostu odziedziczone.

Aby uzyskać więcej informacji, zobacz System.Reflection.BindingFlags.

W przypadku platformy .NET 6 i starszych wersji GetProperties metoda nie zwraca właściwości w określonej kolejności, takiej jak alfabetyczne lub kolejność deklaracji. Kod nie może zależeć od kolejności zwracanej właściwości, ponieważ ta kolejność różni się. Jednak począwszy od platformy .NET 7 kolejność jest deterministyczna na podstawie kolejności metadanych w zestawie.

Jeśli bieżący Type reprezentuje skonstruowany typ ogólny, ta metoda zwraca PropertyInfo obiekty z parametrami typu zastąpionymi przez odpowiednie argumenty typu.

Jeśli bieżący Type reprezentuje parametr typu w definicji typu ogólnego lub metody ogólnej, ta metoda wyszukuje właściwości ograniczenia klasy.

Zobacz też

Dotyczy