PropertyInfo.GetAccessors Método

Definição

Retorna uma matriz dos acessadores get e set nesta propriedade.

Sobrecargas

GetAccessors()

Retorna uma matriz cujos elementos refletem os acessadores get e set públicos da propriedade refletida pela instância atual.

GetAccessors(Boolean)

Retorna uma matriz cujos elementos refletem o público e, se especificado, acessadores set e get não públicos da propriedade refletida pela instância atual.

GetAccessors()

Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs

Retorna uma matriz cujos elementos refletem os acessadores get e set públicos da propriedade refletida pela instância atual.

C#
public System.Reflection.MethodInfo[] GetAccessors();

Retornos

Uma matriz de objetos MethodInfo que refletem os acessadores get e set públicos da propriedade refletida pela instância atual, se encontrada, caso contrário, esse método retorna uma matriz com zero (0) elementos.

Implementações

Exemplos

O exemplo a seguir recupera os acessadores públicos da ClassWithProperty.Caption propriedade e exibe informações sobre eles. Ele também chama o Invoke método do setter para definir o valor da propriedade e do getter para recuperar o valor da propriedade.

C#
using System;
using System.Reflection;
 
// Define a property.
public class ClassWithProperty
{
    private string _caption = "A Default caption";

    public string Caption
    {
        get { return _caption; }
        set { if(_caption != value) _caption = value; }
    }
}
 
class Example
{
    public static void Main()
    {
        ClassWithProperty test = new ClassWithProperty();
        Console.WriteLine("The Caption property: {0}", test.Caption);
        Console.WriteLine("----------");
        // Get the type and PropertyInfo.
        Type t = Type.GetType("ClassWithProperty");
        PropertyInfo propInfo = t.GetProperty("Caption");
 
        // Get the public GetAccessors method.
        MethodInfo[] methInfos = propInfo.GetAccessors();
        Console.WriteLine("There are {0} accessors.",
                          methInfos.Length);
        for(int ctr = 0; ctr < methInfos.Length; ctr++) {
           MethodInfo m = methInfos[ctr];
           Console.WriteLine("Accessor #{0}:", ctr + 1);
           Console.WriteLine("   Name: {0}", m.Name);
           Console.WriteLine("   Visibility: {0}", GetVisibility(m));
           Console.Write("   Property Type: ");
           // Determine if this is the property getter or setter.
           if (m.ReturnType == typeof(void)) {
              Console.WriteLine("Setter");
              Console.WriteLine("   Setting the property value.");
              //  Set the value of the property.
              m.Invoke(test, new object[] { "The Modified Caption" } );
           }
           else {
              Console.WriteLine("Getter");
              // Get the value of the property.
              Console.WriteLine("   Property Value: {0}",
                                m.Invoke(test, new object[] {} ));
           }
        }
        Console.WriteLine("----------");
        Console.WriteLine("The Caption property: {0}", test.Caption);
    }

    static string GetVisibility(MethodInfo m)
    {
       string visibility = "";
       if (m.IsPublic)
          return "Public";
       else if (m.IsPrivate)
          return "Private";
       else
          if (m.IsFamily)
             visibility = "Protected ";
          else if (m.IsAssembly)
             visibility += "Assembly";
       return visibility;
    }
}
// The example displays the following output:
//       The Caption property: A Default caption
//       ----------
//       There are 2 accessors.
//       Accessor #1:
//          Name: get_Caption
//          Visibility: Public
//          Property Type: Getter
//          Property Value: A Default caption
//       Accessor #2:
//          Name: set_Caption
//          Visibility: Public
//          Property Type: Setter
//          Setting the property value.
//       ----------
//       The Caption property: The Modified Caption

Comentários

Para chamar o GetAccessors método :

  1. Obtenha um Type objeto que representa a classe .

  2. Type No objeto , obtenha o PropertyInfo objeto .

  3. PropertyInfo No objeto , chame o GetAccessors método .

Aplica-se a

.NET 10 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.5, 1.6, 2.0, 2.1

GetAccessors(Boolean)

Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs

Retorna uma matriz cujos elementos refletem o público e, se especificado, acessadores set e get não públicos da propriedade refletida pela instância atual.

C#
public abstract System.Reflection.MethodInfo[] GetAccessors(bool nonPublic);

Parâmetros

nonPublic
Boolean

Indica se os métodos não públicos devem ser retornados na matriz retornada. true se os métodos não públicos devem ser incluídos; caso contrário, false.

Retornos

Uma matriz cujos elementos refletem os acessadores get e set da propriedade refletida pela instância atual. Se nonPublic for true, essa matriz conterá acessadores get e set públicos e não públicos. Se nonPublic for false, essa matriz conterá apenas acessadores get e set públicos. Se nenhum acessador com a visibilidade especificada for encontrado, esse método retornará uma matriz com zero (0) elemento.

Implementações

Exemplos

O exemplo a seguir recupera os acessadores da ClassWithProperty.Caption propriedade e exibe informações sobre eles. Ele também chama o Invoke método do setter para definir o valor da propriedade e do getter para recuperar o valor da propriedade.

C#
using System;
using System.Reflection;

// Define a property.
public class ClassWithProperty
{
    private string _caption = "A Default caption";

    public string Caption
    {
        get { return _caption; }
        set { if(_caption != value) _caption = value; }
    }
}

class Example
{
    public static void Main()
    {
        ClassWithProperty test = new ClassWithProperty();
        Console.WriteLine("The Caption property: {0}", test.Caption);
        Console.WriteLine("----------");
        // Get the type and PropertyInfo.
        Type t = Type.GetType("ClassWithProperty");
        PropertyInfo propInfo = t.GetProperty("Caption");

        // Get the public GetAccessors method.
        MethodInfo[] methInfos = propInfo.GetAccessors(true);
        Console.WriteLine("There are {0} accessors.",
                          methInfos.Length);
        for(int ctr = 0; ctr < methInfos.Length; ctr++) {
           MethodInfo m = methInfos[ctr];
           Console.WriteLine("Accessor #{0}:", ctr + 1);
           Console.WriteLine("   Name: {0}", m.Name);
           Console.WriteLine("   Visibility: {0}", GetVisibility(m));
           Console.Write("   Property Type: ");
           // Determine if this is the property getter or setter.
           if (m.ReturnType == typeof(void)) {
              Console.WriteLine("Setter");
              Console.WriteLine("   Setting the property value.");
              //  Set the value of the property.
              m.Invoke(test, new object[] { "The Modified Caption" } );
           }
           else {
              Console.WriteLine("Getter");
              // Get the value of the property.
              Console.WriteLine("   Property Value: {0}",
                                m.Invoke(test, new object[] {} ));
           }
        }
        Console.WriteLine("----------");
        Console.WriteLine("The Caption property: {0}", test.Caption);
    }

    static string GetVisibility(MethodInfo m)
    {
       string visibility = "";
       if (m.IsPublic)
          return "Public";
       else if (m.IsPrivate)
          return "Private";
       else
          if (m.IsFamily)
             visibility = "Protected ";
          else if (m.IsAssembly)
             visibility += "Assembly";
       return visibility;
    }
}
// The example displays the following output:
//       The Caption property: A Default caption
//       ----------
//       There are 2 accessors.
//       Accessor #1:
//          Name: get_Caption
//          Visibility: Public
//          Property Type: Getter
//          Property Value: A Default caption
//       Accessor #2:
//          Name: set_Caption
//          Visibility: Public
//          Property Type: Setter
//          Setting the property value.
//       ----------
//       The Caption property: The Modified Caption

Comentários

Para chamar o GetAccessors método :

  1. Obtenha um Type objeto que representa a classe .

  2. Type No objeto , obtenha o PropertyInfo objeto .

  3. PropertyInfo No objeto , chame o GetAccessors método .

Aplica-se a

.NET 10 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.5, 1.6, 2.0, 2.1