PropertyInfo.GetValue Metode

Definisi

Mengembalikan nilai properti dari objek tertentu.

Overload

GetValue(Object)

Mengembalikan nilai properti dari objek tertentu.

GetValue(Object, Object[])

Mengembalikan nilai properti objek tertentu dengan nilai indeks opsional untuk properti terindeks.

GetValue(Object, BindingFlags, Binder, Object[], CultureInfo)

Saat ditimpa di kelas turunan, mengembalikan nilai properti dari objek tertentu yang memiliki informasi pengikatan, indeks, dan khusus budaya yang ditentukan.

GetValue(Object)

Sumber:
PropertyInfo.cs
Sumber:
PropertyInfo.cs
Sumber:
PropertyInfo.cs

Mengembalikan nilai properti dari objek tertentu.

public:
 System::Object ^ GetValue(System::Object ^ obj);
public object GetValue (object obj);
public object? GetValue (object? obj);
member this.GetValue : obj -> obj
Public Function GetValue (obj As Object) As Object

Parameter

obj
Object

Objek yang nilai propertinya akan dikembalikan.

Mengembalikan

Nilai properti dari objek yang ditentukan.

Contoh

Contoh berikut mendefinisikan Planet kelas yang memiliki dua properti: Name, nama planet; dan Distance, jarak planet dari Bumi. Contoh membuat instans Planet objek yang mewakili planet Jupiter dan meneruskannya ke GetPropertyValues metode yang menampilkan informasi tentang properti dan menggunakan GetValue metode untuk mendapatkan nilai setiap Planet properti.

using System;
using System.Reflection;

public class Planet
{
   private String planetName;
   private Double distanceFromEarth;
   
   public Planet(String name, Double distance)
   {
      planetName = name;
      distanceFromEarth = distance;
   } 

   public String Name
   { get { return planetName; } }
   
   public Double Distance 
   { get { return distanceFromEarth; }
     set { distanceFromEarth = value; } }
}

public class Example
{
   public static void Main()
   {
      Planet jupiter = new Planet("Jupiter", 3.65e08);
      GetPropertyValues(jupiter);
   }
   
   private static void GetPropertyValues(Object obj)
   {
      Type t = obj.GetType();
      Console.WriteLine("Type is: {0}", t.Name);
      PropertyInfo[] props = t.GetProperties();
      Console.WriteLine("Properties (N = {0}):", 
                        props.Length);
      foreach (var prop in props)
         if (prop.GetIndexParameters().Length == 0)
            Console.WriteLine("   {0} ({1}): {2}", prop.Name,
                              prop.PropertyType.Name,
                              prop.GetValue(obj));
         else
            Console.WriteLine("   {0} ({1}): <Indexed>", prop.Name,
                              prop.PropertyType.Name);
   }
}
// The example displays the following output:
//       Type is: Planet
//       Properties (N = 2):
//          Name (String): Jupiter
//          Distance (Double): 365000000
Imports System.Reflection

Public Class Planet
   Private planetName As String
   Private distanceFromEarth As Double
   
   Public Sub New(name As String, distance As Double)
      planetName = name
      distanceFromEarth = distance
   End Sub 

   Public ReadOnly Property Name As String
      Get
         Return planetName
      End Get
   End Property
   
   Public Property Distance As Double
      Get
         Return distanceFromEarth
      End Get
      Set
         distanceFromEarth = value
      End Set
   End Property
End Class

Module Example
   Public Sub Main()
      Dim jupiter As New Planet("Jupiter", 3.65e08)
      GetPropertyValues(jupiter)
   End Sub
   
   Private Sub GetPropertyValues(obj As Object)
      Dim t As Type = obj.GetType()
      Console.WriteLine("Type is: {0}", t.Name)
      Dim props() As PropertyInfo = t.GetProperties()
      Console.WriteLine("Properties (N = {0}):", 
                        props.Length)
      For Each prop In props
         If prop.GetIndexParameters().Length = 0 Then
            Console.WriteLine("   {0} ({1}): {2}", prop.Name,
                              prop.PropertyType.Name,
                              prop.GetValue(obj))
         Else
            Console.WriteLine("   {0} ({1}): <Indexed>", prop.Name,
                              prop.PropertyType.Name)
         End If                  
      Next                         
   End Sub
End Module
' The example displays the following output:
'       Type is: Planet
'       Properties (N = 2):
'          Name (String): Jupiter
'          Distance (Double): 365000000

Keterangan

Anda memanggil GetValue(Object) kelebihan beban untuk mengambil nilai properti yang tidak diindeks; jika Anda mencoba mengambil nilai properti terindeks, metode akan memberikan TargetParameterCountException pengecualian. Anda dapat menentukan apakah properti diindeks atau tidak dengan memanggil GetIndexParameters metode . Jika panjang array yang dikembalikan ParameterInfo adalah nol, properti tidak diindeks.

Ini adalah metode kenyamanan yang menyediakan implementasi untuk metode abstrak GetValue(Object, BindingFlags, Binder, Object[], CultureInfo) dengan parameter yang BindingFlags diatur ke , Binder diatur ke nullBindingFlags.Default, array objek nilai indeks diatur ke null, dan CultureInfo diatur ke null.

Berlaku untuk

GetValue(Object, Object[])

Sumber:
PropertyInfo.cs
Sumber:
PropertyInfo.cs
Sumber:
PropertyInfo.cs

Mengembalikan nilai properti objek tertentu dengan nilai indeks opsional untuk properti terindeks.

public:
 virtual System::Object ^ GetValue(System::Object ^ obj, cli::array <System::Object ^> ^ index);
public virtual object GetValue (object obj, object[] index);
public virtual object? GetValue (object? obj, object?[]? index);
abstract member GetValue : obj * obj[] -> obj
override this.GetValue : obj * obj[] -> obj
Public Overridable Function GetValue (obj As Object, index As Object()) As Object

Parameter

obj
Object

Objek yang nilai propertinya akan dikembalikan.

index
Object[]

Nilai indeks opsional untuk properti terindeks. Indeks properti terindeks berbasis nol. Nilai ini harus null untuk properti yang tidak diindeks.

Mengembalikan

Nilai properti dari objek yang ditentukan.

Penerapan

Pengecualian

Array index tidak berisi jenis argumen yang diperlukan.

-atau-

Aksesor properti get tidak ditemukan.

Objek tidak cocok dengan jenis target, atau properti adalah properti instans tetapi obj adalah null.

Catatan: Di .NET untuk aplikasi Bursa Windows atau Pustaka Kelas Portabel, tangkap Exception sebagai gantinya.

Jumlah parameter di index tidak cocok dengan jumlah parameter yang diambil properti terindeks.

Ada upaya ilegal untuk mengakses metode privat atau dilindungi di dalam kelas.

Catatan: Di .NET untuk aplikasi Bursa Windows atau Pustaka Kelas Portabel, tangkap pengecualian kelas dasar, MemberAccessException, sebagai gantinya.

Terjadi kesalahan saat mengambil nilai properti. Misalnya, nilai indeks yang ditentukan untuk properti terindeks berada di luar rentang. Properti InnerException menunjukkan alasan kesalahan.

Contoh

Contoh berikut menunjukkan cara mendapatkan nilai properti terindeks. Properti String.Chars[] adalah properti default (pengindeks di C#) kelas String .

using System;
using System.Reflection;

class Example
{
    public static void Main()
    {
        string test = "abcdefghijklmnopqrstuvwxyz";

        // Get a PropertyInfo object representing the Chars property.
        PropertyInfo pinfo = typeof(string).GetProperty("Chars");

        // Show the first, seventh, and last letters
        ShowIndividualCharacters(pinfo, test, 0, 6, test.Length - 1);

        // Show the complete string.
        Console.Write("The entire string: ");
        for (int x = 0; x < test.Length; x++)
        {
            Console.Write(pinfo.GetValue(test, new Object[] {x}));
        }
        Console.WriteLine();
    }

    static void ShowIndividualCharacters(PropertyInfo pinfo, 
                                         object value,
                                         params int[] indexes)
    {
       foreach (var index in indexes) 
          Console.WriteLine("Character in position {0,2}: '{1}'",
                            index, pinfo.GetValue(value, new object[] { index }));
       Console.WriteLine();                          
    }                                      
}
// The example displays the following output:
//    Character in position  0: 'a'
//    Character in position  6: 'g'
//    Character in position 25: 'z'
//    
//    The entire string: abcdefghijklmnopqrstuvwxyz
Imports System.Reflection

Module Example
    Sub Main()
        Dim test As String = "abcdefghijklmnopqrstuvwxyz"

        ' Get a PropertyInfo object representing the Chars property.
        Dim pinfo As PropertyInfo = GetType(String).GetProperty("Chars")

        ' Show the first, seventh, and last characters.
        ShowIndividualCharacters(pinfo, test, { 0, 6, test.Length - 1 })

        ' Show the complete string.
        Console.Write("The entire string: ")
        For x As Integer = 0 To test.Length - 1
            Console.Write(pinfo.GetValue(test, { x }))
        Next
        Console.WriteLine()
    End Sub

    Sub ShowIndividualCharacters(pinfo As PropertyInfo, 
                                 value As Object, 
                                 ParamArray indexes() As Integer)
       For Each index In indexes 
          Console.WriteLine("Character in position {0,2}: '{1}'",
                            index, pinfo.GetValue(value, { index }))
       Next
       Console.WriteLine()                          
    End Sub   
End Module
' The example displays the following output:
'       Character in position  0: 'a'
'       Character in position  6: 'g'
'       Character in position 25: 'z'
'       
'       The entire string: abcdefghijklmnopqrstuvwxyz

Keterangan

Untuk menentukan apakah properti diindeks, gunakan GetIndexParameters metode . Jika array yang dihasilkan memiliki 0 (nol) elemen, properti tidak diindeks.

Ini adalah metode kenyamanan yang menyediakan implementasi untuk metode abstrak dengan parameter , yang diatur ke null, dan CultureInfo diatur ke null.BinderDefaultBindingFlagsGetValue

Karena properti statis milik jenis, bukan objek individual, dapatkan properti statis dengan meneruskan null sebagai argumen objek. Misalnya, gunakan kode berikut untuk mendapatkan properti statis CurrentCulture dari CultureInfo :

PropertyInfo CurCultProp =
    (typeof(CultureInfo)).GetProperty("CurrentCulture");
Console.WriteLine("CurrCult: " +
    CurCultProp.GetValue(null,null));

Untuk menggunakan metode , GetValue pertama-tama dapatkan kelas Type. TypeDari , dapatkan PropertyInfo. PropertyInfoDari , gunakan GetValue metode .

Catatan

Dimulai dengan .NET Framework 2.0, metode ini dapat digunakan untuk mengakses anggota non-publik jika pemanggil telah diberikan ReflectionPermission dengan ReflectionPermissionFlag.RestrictedMemberAccess bendera dan jika set pemberian anggota non-publik dibatasi untuk set pemberian pemanggil, atau subsetnya. (Lihat Pertimbangan Keamanan untuk Refleksi.) Untuk menggunakan fungsionalitas ini, aplikasi Anda harus menargetkan .NET Framework 3.5 atau yang lebih baru.

Berlaku untuk

GetValue(Object, BindingFlags, Binder, Object[], CultureInfo)

Sumber:
PropertyInfo.cs
Sumber:
PropertyInfo.cs
Sumber:
PropertyInfo.cs

Saat ditimpa di kelas turunan, mengembalikan nilai properti dari objek tertentu yang memiliki informasi pengikatan, indeks, dan khusus budaya yang ditentukan.

public:
 abstract System::Object ^ GetValue(System::Object ^ obj, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ index, System::Globalization::CultureInfo ^ culture);
public abstract object? GetValue (object? obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? index, System.Globalization.CultureInfo? culture);
public abstract object GetValue (object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] index, System.Globalization.CultureInfo culture);
abstract member GetValue : obj * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> obj
Public MustOverride Function GetValue (obj As Object, invokeAttr As BindingFlags, binder As Binder, index As Object(), culture As CultureInfo) As Object

Parameter

obj
Object

Objek yang nilai propertinya akan dikembalikan.

invokeAttr
BindingFlags

Kombinasi bit dari anggota enumerasi berikut yang menentukan atribut pemanggilan: InvokeMethod, , CreateInstance, StaticGetField, SetField, GetProperty, dan SetProperty. Anda harus menentukan atribut pemanggilan yang sesuai. Misalnya, untuk memanggil anggota statis, atur Static bendera .

binder
Binder

Objek yang memungkinkan pengikatan, pemaksian jenis argumen, pemanggilan anggota, dan MemberInfo pengambilan objek melalui refleksi. Jika binder adalah null, pengikat default digunakan.

index
Object[]

Nilai indeks opsional untuk properti terindeks. Nilai ini harus null untuk properti yang tidak diindeks.

culture
CultureInfo

Budaya yang sumber dayanya akan dilokalkan. Jika sumber daya tidak dilokalkan untuk budaya ini, Parent properti akan dipanggil secara berturut-turut untuk mencari kecocokan. Jika nilai ini adalah null, informasi khusus budaya diperoleh dari CurrentUICulture properti .

Mengembalikan

Nilai properti dari objek yang ditentukan.

Penerapan

Pengecualian

Array index tidak berisi jenis argumen yang diperlukan.

-atau-

Aksesor properti get tidak ditemukan.

Objek tidak cocok dengan jenis target, atau properti adalah properti instans tetapi obj adalah null.

Jumlah parameter di index tidak cocok dengan jumlah parameter yang diambil properti terindeks.

Ada upaya ilegal untuk mengakses metode privat atau dilindungi di dalam kelas.

Terjadi kesalahan saat mengambil nilai properti. Misalnya, nilai indeks yang ditentukan untuk properti terindeks berada di luar rentang. Properti InnerException menunjukkan alasan kesalahan.

Keterangan

Untuk menentukan apakah properti diindeks, gunakan GetIndexParameters metode . Jika array yang dihasilkan memiliki 0 (nol) elemen, properti tidak diindeks.

Karena properti statis milik jenis, bukan objek individual, dapatkan properti statis dengan meneruskan null sebagai argumen objek. Misalnya, gunakan kode berikut untuk mendapatkan properti statis CurrentCulture dari CultureInfo :

PropertyInfo CurCultProp =
       (typeof(CultureInfo)).GetProperty("CurrentCulture");
Console.WriteLine("CurrCult: " +
       CurCultProp.GetValue(null,null));

Untuk menggunakan metode , GetValue pertama-tama dapatkan kelas Type. TypeDari , dapatkan PropertyInfo. PropertyInfoDari , gunakan GetValue metode .

Catatan

Dimulai dengan .NET Framework 2.0, metode ini dapat digunakan untuk mengakses anggota non-publik jika pemanggil telah diberikan ReflectionPermission dengan ReflectionPermissionFlag.RestrictedMemberAccess bendera dan jika set pemberian anggota non-publik dibatasi untuk set pemberian pemanggil, atau subsetnya. (Lihat Pertimbangan Keamanan untuk Refleksi.) Untuk menggunakan fungsionalitas ini, aplikasi Anda harus menargetkan .NET Framework 3.5 atau yang lebih baru.

Lihat juga

Berlaku untuk