PropertyInfo.GetValue 方法

定義

傳回指定的物件的屬性值。

多載

GetValue(Object)

傳回指定的物件的屬性值。

GetValue(Object, Object[])

傳回指定的物件的屬性值,和索引屬性的選擇性索引值。

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

當在衍生類別中覆寫時,傳回指定的物件的屬性值,此物件具有指定的繫結、索引和文化特性特定資訊。

GetValue(Object)

來源:
PropertyInfo.cs
來源:
PropertyInfo.cs
來源:
PropertyInfo.cs

傳回指定的物件的屬性值。

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

參數

obj
Object

其屬性值將被傳回的物件。

傳回

指定之物件的屬性值。

範例

下列範例會定義具有兩個 Planet 屬性的類別: Name 、行星的名稱,以及 Distance 行星與地球的距離。 此範例會具現化 Planet 代表行星 Jupiter 的物件,並將它 GetPropertyValues 傳遞給顯示內容相關資訊的方法,並使用 GetValue 方法來取得每個 Planet 屬性的值。

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

備註

您可以呼叫 GetValue(Object) 多載來擷取非索引屬性的值;如果您嘗試擷取索引屬性的值,方法會 TargetParameterCountException 擲回例外狀況。 您可以呼叫 GetIndexParameters 方法來判斷屬性是否編制索引。 如果傳 ParameterInfo 回的陣列長度為零,則屬性不會編制索引。

這是一個便利的方法,提供抽象 GetValue(Object, BindingFlags, Binder, Object[], CultureInfo) 方法的實作,其中參數設定 BindingFlags.Default 為 、 Binder 設定為 null 、索引值 null 的物件陣列設定為 ,以及 CultureInfo 設定為 nullBindingFlags

適用於

GetValue(Object, Object[])

來源:
PropertyInfo.cs
來源:
PropertyInfo.cs
來源:
PropertyInfo.cs

傳回指定的物件的屬性值,和索引屬性的選擇性索引值。

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

參數

obj
Object

其屬性值將被傳回的物件。

index
Object[]

索引屬性的選擇性索引值。 索引屬性的索引以零為起始。 非索引屬性的這個值應為 null

傳回

指定之物件的屬性值。

實作

例外狀況

index 陣列未包含所需的引數類型。

-或-

找不到屬性的 get 存取子。

物件不符合目標類型,或屬性是執行個體屬性但 objnull

注意:在 適用于 Windows 市集應用程式的 .NET可攜式類別庫中,改為攔截 Exception

index 中的參數數目不符合索引屬性所接受的參數數目。

曾不合法嘗試存取類別內的私用或保護方法。

注意:在 適用于 Windows 市集應用程式的 .NET可攜式類別庫中,改為攔截基類例外狀況 MemberAccessException

擷取屬性值時發生錯誤。 例如,為索引屬性指定的索引值超出範圍。 InnerException 屬性指出錯誤的原因。

範例

下列範例示範如何取得索引屬性的值。 屬性 String.Chars[] 是類別 C# ) 中索引子的預設屬性 (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

備註

若要判斷屬性是否已編制索引,請使用 GetIndexParameters 方法。 如果產生的陣列有 0 (零) 元素,則屬性不會編制索引。

這是一個便利的方法,提供抽象方法的 Default 實作,其 BindingFlags 參數為 、 Binder 設定為 null ,並將 CultureInfo 設定為 nullGetValue

因為靜態屬性屬於類型,而不是個別物件,所以透過傳遞 null 作為物件引數來取得靜態屬性。 例如,使用下列程式碼來取得 的 CultureInfo 靜態 CurrentCulture 屬性:

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

若要使用 GetValue 方法,請先取得 類別 TypeType從 取得 PropertyInfoPropertyInfo從 使用 GetValue 方法。

注意

從 .NET Framework 2.0 開始,如果呼叫端已使用 旗標授 ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess 與呼叫端,而且非公用成員的授與集限制為呼叫端的授與集,或是子集,則這個方法可用來存取非公用成員。 (請參閱 Reflection.) 的安全性考慮若要使用這項功能,您的應用程式應以 3.5 或更新版本為目標.NET Framework。

適用於

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

來源:
PropertyInfo.cs
來源:
PropertyInfo.cs
來源:
PropertyInfo.cs

當在衍生類別中覆寫時,傳回指定的物件的屬性值,此物件具有指定的繫結、索引和文化特性特定資訊。

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

參數

obj
Object

其屬性值將被傳回的物件。

invokeAttr
BindingFlags

下列可指定引動過程屬性之列舉成員的位元組合:InvokeMethodCreateInstanceStaticGetFieldSetFieldGetPropertySetProperty。 您必須指定適當的引動過程屬性。 例如,要叫用靜態成員,就設定 Static 旗標。

binder
Binder

使用反映來啟用繫結、強制引數的類型、成員的引動過程,和擷取 MemberInfo 物件的物件。 如果 bindernull,則會使用預設繫結器。

index
Object[]

索引屬性的選擇性索引值。 非索引屬性的這個值應為 null

culture
CultureInfo

資源要當地語系化的文化特性。 如果未針對這個文化特性將資源當地語系化,則將在搜尋相符項目時持續呼叫 Parent 屬性。 如果這個值是 null,則會從 CurrentUICulture 屬性取得特定文化特性資訊。

傳回

指定之物件的屬性值。

實作

例外狀況

index 陣列未包含所需的引數類型。

-或-

找不到屬性的 get 存取子。

物件不符合目標類型,或屬性是執行個體屬性但 objnull

index 中的參數數目不符合索引屬性所接受的參數數目。

曾不合法嘗試存取類別內的私用或保護方法。

擷取屬性值時發生錯誤。 例如,為索引屬性指定的索引值超出範圍。 InnerException 屬性指出錯誤的原因。

備註

若要判斷屬性是否已編制索引,請使用 GetIndexParameters 方法。 如果產生的陣列有 0 (零) 元素,則屬性不會編制索引。

因為靜態屬性屬於類型,而不是個別物件,所以透過傳遞 null 作為物件引數來取得靜態屬性。 例如,使用下列程式碼來取得 的 CultureInfo 靜態 CurrentCulture 屬性:

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

若要使用 GetValue 方法,請先取得 類別 TypeType從 取得 PropertyInfoPropertyInfo從 使用 GetValue 方法。

注意

從 .NET Framework 2.0 開始,如果呼叫端已使用 旗標授 ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess 與呼叫端,而且非公用成員的授與集限制為呼叫端的授與集,或是子集,則這個方法可用來存取非公用成員。 (請參閱 Reflection.) 的安全性考慮若要使用這項功能,您的應用程式應以 3.5 或更新版本為目標.NET Framework。

另請參閱

適用於