PropertyInfo.GetValue 方法

定义

返回指定对象的属性值。Returns the property value of a specified object.

重载

GetValue(Object)

返回指定对象的属性值。Returns the property value of a specified object.

GetValue(Object, Object[])

用索引化属性的可选索引值返回指定对象的该属性值。Returns the property value of a specified object with optional index values for indexed properties.

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

当在派生类中重写时,将返回具有指定绑定、索引和区域性特定信息的指定对象的属性值。When overridden in a derived class, returns the property value of a specified object that has the specified binding, index, and culture-specific information.

GetValue(Object)

返回指定对象的属性值。Returns the property value of a specified object.

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

将返回其属性值的对象。The object whose property value will be returned.

返回

Object

指定对象的属性值。The property value of the specified object.

示例

下面的示例定义了一个 Planet 具有两个属性的类: Name 、行星的名称和 Distance 地球与地球的距离。The following example defines a Planet class that has two properties: Name, the name of the planet; and Distance, the planet's distance from Earth. 该示例实例化一个 Planet 表示行星木星的对象,并将其传递给一个 GetPropertyValues 方法,该方法显示有关属性的信息,并使用 GetValue 方法获取每个属性的值 PlanetThe example instantiates a Planet object that represents the planet Jupiter and passes it to a GetPropertyValues method that displays information about the properties and uses the GetValue method to get the value of each Planet property.

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 异常。You call the GetValue(Object) overload to retrieve the value of a non-indexed property; if you try to retrieve the value of an indexed property, the method throws a TargetParameterCountException exception. 可以通过调用方法来确定是否已对属性进行索引 GetIndexParametersYou can determine whether a property is indexed or not by calling the GetIndexParameters method. 如果返回数组的长度 ParameterInfo 为零,则不会为该属性编制索引。If the length of the returned ParameterInfo array is zero, the property is not indexed.

这是一种简便方法,可为以下方法提供实现:将 GetValue(Object, BindingFlags, Binder, Object[], CultureInfo) BindingFlags 参数设置为 BindingFlags.Default ,将 Binder 设置为 null ,将索引值的对象数组设置为, null 并将 CultureInfo 设置为 nullThis is a convenience method that provides an implementation for the abstract GetValue(Object, BindingFlags, Binder, Object[], CultureInfo) method with the BindingFlags parameter set to BindingFlags.Default, the Binder set to null, the object array of index values set to null, and the CultureInfo set to null.

适用于

GetValue(Object, Object[])

用索引化属性的可选索引值返回指定对象的该属性值。Returns the property value of a specified object with optional index values for indexed properties.

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

将返回其属性值的对象。The object whose property value will be returned.

index
Object[]

索引化属性的可选索引值。Optional index values for indexed properties. 索引化属性的索引从零开始。The indexes of indexed properties are zero-based. 对于非索引化属性,该值应为 nullThis value should be null for non-indexed properties.

返回

Object

指定对象的属性值。The property value of the specified object.

实现

例外

index 数组不包含所需的参数类型。The index array does not contain the type of arguments needed.

-or- 找不到该属性的 get 取值函数。The property's get accessor is not found.

该对象与目标类型不匹配,或者某属性是实例属性但 objnullThe object does not match the target type, or a property is an instance property but obj is null.

index 中的参数数量与索引属性采用的参数数量不匹配。The number of parameters in index does not match the number of parameters the indexed property takes.

试图非法访问类中的私有或受保护方法。There was an illegal attempt to access a private or protected method inside a class.

检索属性值时出错。An error occurred while retrieving the property value. 例如,为一个索引属性指定的索引值超出范围。For example, an index value specified for an indexed property is out of range. InnerException 属性指示出错的原因。The InnerException property indicates the reason for the error.

示例

下面的示例演示如何获取索引属性的值。The following example shows how to get the value of an indexed property. String.Chars[]属性是类的 c # ) 中 (索引器的默认属性 StringThe String.Chars[] property is the default property (the indexer in C#) of the String class.

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 方法。To determine whether a property is indexed, use the GetIndexParameters method. 如果生成的数组有0个 (零) 元素,则不会为该属性编制索引。If the resulting array has 0 (zero) elements, the property is not indexed.

这是一种便捷的方法,它为使用的 GetValue BindingFlags 参数 DefaultBinder 设置为的 nullCultureInfo 设置为 null 的抽象方法提供实现。This is a convenience method that provides an implementation for the abstract GetValue method with a BindingFlags parameter of Default, the Binder set to null, and the CultureInfo set to null.

由于静态属性属于类型,而不属于单个对象,因此通过将作为对象参数传递来获取静态属性 nullBecause static properties belong to the type, not individual objects, get static properties by passing null as the object argument. 例如,使用以下代码获取 CurrentCulture 的静态属性 CultureInfoFor example, use the following code to get the static CurrentCulture property of CultureInfo :

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

若要使用 GetValue 方法,请首先获取类 TypeTo use the GetValue method, first get the class Type. 从中 Type 获取 PropertyInfoFrom the Type, get the PropertyInfo. 从中 PropertyInfo ,使用 GetValue 方法。From the PropertyInfo, use the GetValue method.

备注

从 .NET Framework 2.0 Service Pack 1 开始,此方法可用于访问非公共成员(如果调用方已 ReflectionPermission 使用 ReflectionPermissionFlag.RestrictedMemberAccess 标志授予),并且如果非公共成员的授予集限制为调用方的授予集或其子集,则可使用此方法访问非公共成员。Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (参阅 反射的安全注意事项) (See Security Considerations for Reflection.)

若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5 or later.

适用于

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

当在派生类中重写时,将返回具有指定绑定、索引和区域性特定信息的指定对象的属性值。When overridden in a derived class, returns the property value of a specified object that has the specified binding, index, and culture-specific information.

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

将返回其属性值的对象。The object whose property value will be returned.

invokeAttr
BindingFlags

以下指定该调用特性的枚举成员的按位组合: InvokeMethodCreateInstanceStaticGetFieldSetFieldGetPropertySetPropertyA bitwise combination of the following enumeration members that specify the invocation attribute: InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty, and SetProperty. 必须指定合适的调用属性。You must specify a suitable invocation attribute. 例如,为了调用静态成员,设置 Static 标志。For example, to invoke a static member, set the Static flag.

binder
Binder

一个对象,它启用绑定、对参数类型的强制、对成员的调用,以及通过反射对 MemberInfo 对象的检索。An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

index
Object[]

索引化属性的可选索引值。Optional index values for indexed properties. 对于非索引化属性,该值应为 nullThis value should be null for non-indexed properties.

culture
CultureInfo

要为其本地化资源的区域性。The culture for which the resource is to be localized. 请注意,如果没有为此区域性本地化该资源,则在搜索匹配项的过程中将继续调用 Parent 属性。If the resource is not localized for this culture, the Parent property will be called successively in search of a match. 如果该值为 null,则从 CurrentUICulture 属性获取区域性的特定信息。If this value is null, the culture-specific information is obtained from the CurrentUICulture property.

返回

Object

指定对象的属性值。The property value of the specified object.

实现

例外

index 数组不包含所需的参数类型。The index array does not contain the type of arguments needed.

-or- 找不到该属性的 get 取值函数。The property's get accessor is not found.

该对象与目标类型不匹配,或者某属性是实例属性但 objnullThe object does not match the target type, or a property is an instance property but obj is null.

index 中的参数数量与索引属性采用的参数数量不匹配。The number of parameters in index does not match the number of parameters the indexed property takes.

试图非法访问类中的私有或受保护方法。There was an illegal attempt to access a private or protected method inside a class.

检索属性值时出错。An error occurred while retrieving the property value. 例如,为一个索引属性指定的索引值超出范围。For example, an index value specified for an indexed property is out of range. InnerException 属性指示出错的原因。The InnerException property indicates the reason for the error.

注解

若要确定是否已对某个属性编制索引,请使用 GetIndexParameters 方法。To determine whether a property is indexed, use the GetIndexParameters method. 如果生成的数组有0个 (零) 元素,则不会为该属性编制索引。If the resulting array has 0 (zero) elements, the property is not indexed.

由于静态属性属于类型,而不属于单个对象,因此通过将作为对象参数传递来获取静态属性 nullBecause static properties belong to the type, not individual objects, get static properties by passing null as the object argument. 例如,使用以下代码获取 CurrentCulture 的静态属性 CultureInfoFor example, use the following code to get the static CurrentCulture property of CultureInfo :

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

若要使用 GetValue 方法,请首先获取类 TypeTo use the GetValue method, first get the class Type. 从中 Type 获取 PropertyInfoFrom the Type, get the PropertyInfo. 从中 PropertyInfo ,使用 GetValue 方法。From the PropertyInfo, use the GetValue method.

备注

从 .NET Framework 2.0 Service Pack 1 开始,此方法可用于访问非公共成员(如果调用方已 ReflectionPermission 使用 ReflectionPermissionFlag.RestrictedMemberAccess 标志授予),并且如果非公共成员的授予集限制为调用方的授予集或其子集,则可使用此方法访问非公共成员。Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (参阅 反射的安全注意事项) (See Security Considerations for Reflection.)

若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5 or later.

另请参阅

适用于