Uredi

Deli z drugimi prek


PropertyInfo.GetValue Method

Definition

Returns the property value of a specified object.

Overloads

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)

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

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

Parameters

obj
Object

The object whose property value will be returned.

Returns

The property value of the specified object.

Examples

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. The 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

Remarks

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. You can determine whether a property is indexed or not by calling the GetIndexParameters method. If the length of the returned ParameterInfo array is zero, the property is not indexed.

This 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.

Applies to

GetValue(Object, Object[])

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

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

Parameters

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. This value should be null for non-indexed properties.

Returns

The property value of the specified object.

Implements

Exceptions

The index array does not contain the type of arguments needed.

-or-

The property's get accessor is not found.

The object does not match the target type, or a property is an instance property but obj is null.

Note: In .NET for Windows Store apps or the Portable Class Library, catch Exception instead.

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.

Note: In .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.

An error occurred while retrieving the property value. For example, an index value specified for an indexed property is out of range. The InnerException property indicates the reason for the error.

Examples

The following example shows how to get the value of an indexed property. The 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

Remarks

To determine whether a property is indexed, use the GetIndexParameters method. If the resulting array has 0 (zero) elements, the property is not indexed.

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.

Because static properties belong to the type, not individual objects, get static properties by passing null as the object argument. For 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));

To use the GetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetValue method.

Note

Starting with .NET Framework 2.0, 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.) To use this functionality, your application should target .NET Framework 3.5 or later.

Applies to

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

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

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

Parameters

obj
Object

The object whose property value will be returned.

invokeAttr
BindingFlags

A 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. For example, to invoke a static member, set the Static flag.

binder
Binder

An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. If binder is null, the default binder is used.

index
Object[]

Optional index values for indexed properties. This value should be null for non-indexed properties.

culture
CultureInfo

The culture for which the resource is to be localized. If the resource is not localized for this culture, the Parent property will be called successively in search of a match. If this value is null, the culture-specific information is obtained from the CurrentUICulture property.

Returns

The property value of the specified object.

Implements

Exceptions

The index array does not contain the type of arguments needed.

-or-

The property's get accessor is not found.

The object does not match the target type, or a property is an instance property but obj is null.

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. The InnerException property indicates the reason for the error.

Remarks

To determine whether a property is indexed, use the GetIndexParameters method. If the resulting array has 0 (zero) elements, the property is not indexed.

Because static properties belong to the type, not individual objects, get static properties by passing null as the object argument. For 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));

To use the GetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetValue method.

Note

Starting with .NET Framework 2.0, 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.) To use this functionality, your application should target .NET Framework 3.5 or later.

See also

Applies to