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

プロパティ値が返されるオブジェクト。

戻り値

指定されたオブジェクトのプロパティの値。

次の例では、2 つのプロパティNamePlanet持つクラス (惑星の名前) と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 配列の長さが 0 の場合、 プロパティのインデックスは作成されません。

これは、抽象GetValue(Object, BindingFlags, Binder, Object[], CultureInfo)メソッドの実装を提供する便利なメソッドでBindingFlags、 パラメーターを に設定し、 を にnullBindingFlags.DefaultBinder設定し、インデックス値のオブジェクト配列を にnull設定し、 を CultureInfo に設定しますnull

適用対象

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[]

インデックス付きプロパティのインデックス値 (省略可能)。 インデックス付きプロパティのインデックスは 0 から始まります。 インデックス付きでないプロパティの場合は、この値を null にする必要があります。

戻り値

指定されたオブジェクトのプロパティの値。

実装

例外

必要な引数の型が index 配列に含まれていません。

または

プロパティの get アクセサーが見つかりません。

オブジェクトがターゲット型と一致しません。あるいは、プロパティはインスタンス プロパティですが objnull です。

注: .NET for Windows ストア アプリ または ポータブル クラス ライブラリでは、代わりに catch を使用 Exception します。

index 内のパラメーターの数が、インデックス付きプロパティが受け取るパラメーターの数と一致していません。

クラス内のプライベート メソッドまたは保護されたメソッドへの正しくないアクセスが試行されました。

注: .NET for Windows ストア アプリ または ポータブル クラス ライブラリでは、代わりに基底クラスの例外 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 (ゼロ) の要素がある場合、プロパティのインデックスは作成されません。

これは、抽象GetValueメソッドの実装を、パラメーターDefaultBinderを に設定し、 を にnull設定して提供するnull便利なCultureInfoメソッドBindingFlagsです。

静的プロパティは個々のオブジェクトではなく型に属しているため、 オブジェクト引数として を渡 null すことで静的プロパティを取得します。 たとえば、 の静的 CurrentCulture プロパティを取得するには、次の CultureInfo コードを使用します。

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

メソッドを使用するには、最初に GetValue クラス Typeを取得します。 から、 Typeを取得します PropertyInfo。 から、 PropertyInfoメソッドを使用します GetValue

Note

.NET Framework 2.0 以降では、このメソッドを使用して、呼び出し元が フラグを使用ReflectionPermissionFlag.RestrictedMemberAccessして許可ReflectionPermissionされている場合、および非パブリック メンバーの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合に、非パブリック メンバーにアクセスできます。 (リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

適用対象

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 すことで静的プロパティを取得します。 たとえば、 の静的 CurrentCulture プロパティを取得するには、次の CultureInfo コードを使用します。

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

メソッドを使用するには、最初に GetValue クラス Typeを取得します。 から、 Typeを取得します PropertyInfo。 から、 PropertyInfoメソッドを使用します GetValue

Note

.NET Framework 2.0 以降では、このメソッドを使用して、呼び出し元が フラグを使用ReflectionPermissionFlag.RestrictedMemberAccessして許可ReflectionPermissionされている場合、および非パブリック メンバーの許可セットが呼び出し元の許可セットまたはそのサブセットに制限されている場合に、非パブリック メンバーにアクセスできます。 (リフレクションのセキュリティに関する考慮事項に関するページを参照してください)。この機能を使用するには、アプリケーションで .NET Framework 3.5 以降をターゲットにする必要があります。

こちらもご覧ください

適用対象