PropertyInfo.GetValue 메서드

정의

지정된 개체의 속성 값을 반환합니다.

오버로드

GetValue(Object)

지정된 개체의 속성 값을 반환합니다.

GetValue(Object, Object[])

인덱싱된 속성에 대해 선택적인 인덱스 값이 있는 지정된 개체의 속성 값을 반환합니다.

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

파생된 클래스에서 재정의된 경우 지정된 바인딩, 인덱스 및 문화별 정보가 있는 지정된 개체의 속성 값을 반환합니다.

GetValue(Object)

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
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

속성 값이 반환될 개체입니다.

반환

지정된 개체의 속성 값입니다.

예제

다음 예제에서는 두 가지 속성Name이 있는 클래스를 Planet 정의합니다. 즉, 행성의 이름, 지구Distance로부터 행성의 거리입니다. 이 예제에서는 목성 행성을 Planet 나타내는 개체를 인스턴스화하고 속성에 대한 정보를 표시하고 메서드를 사용하여 GetValuePlanet 속성의 값을 가져오는 메서드에 전달 GetPropertyValues 합니다.

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 throw합니다. 메서드를 호출 GetIndexParameters 하여 속성이 인덱싱되는지 여부를 확인할 수 있습니다. 반환 ParameterInfo 된 배열의 길이가 0이면 속성이 인덱싱되지 않습니다.

매개 변수를 로 설정하고, 로 설정하고BindingFlags.Default, 인덱스 값의 개체 배열을 로 설정하고null, Binder 를 로 설정null하여 추상 GetValue(Object, BindingFlags, Binder, Object[], CultureInfo) 메서드 BindingFlags 에 대한 구현을 nullCultureInfo 제공하는 편리한 메서드입니다.

적용 대상

GetValue(Object, Object[])

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
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입니다.

참고: Windows 스토어 앱 또는 이식 가능한 클래스 라이브러리용 .NET에서 대신 catch Exception 합니다.

index의 매개 변수 개수가 인덱싱된 속성 작업의 매개 변수 개수와 일치하지 않습니다.

클래스 내에서 개인 메서드 또는 보호된 메서드에 액세스하려는 잘못된 시도가 있었습니다.

참고: Windows 스토어 앱 또는 이식 가능한 클래스 라이브러리용 .NET에서 기본 클래스 예외 를 MemberAccessException대신 catch합니다.

속성 값을 검색하는 동안 오류가 발생했습니다. 예를 들어, 인덱싱된 속성에 대해 지정된 인덱스 값이 범위를 벗어났습니다. 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를 사용하여 추상 GetValue 메서드에 대한 구현을 BindingFlags 제공하고, 를 로 null설정하고, BinderCultureInfo 를 로 null설정하는 편리한 메서드입니다.

정적 속성은 개별 개체가 아닌 형식에 속하므로 개체 인수로 전달 null 하여 정적 속성을 가져옵니다. 예를 들어 다음 코드를 사용하여 의 CultureInfo 정적 CurrentCulture 속성을 가져옵니다.

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

메서드를 GetValue 사용하려면 먼저 클래스 Type를 가져옵니다. 에서 를 Type가져옵니다 PropertyInfo. 에서 PropertyInfo메서드를 GetValue 사용합니다.

참고

.NET Framework 2.0부터 이 메서드는 호출자가 플래그를 ReflectionPermissionFlag.RestrictedMemberAccess 사용하여 부여된 ReflectionPermission 경우 및 비공용 멤버의 권한 부여 집합이 호출자의 권한 부여 집합 또는 해당 하위 집합으로 제한되는 경우 비공용 멤버에 액세스하는 데 사용할 수 있습니다. (리플렉션에 대한 보안 고려 사항을 참조하세요.) 이 기능을 사용하려면 애플리케이션이 .NET Framework 3.5 이상을 대상으로 해야 합니다.

적용 대상

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

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
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

호출 특성을 지정하는 InvokeMethod, CreateInstance, Static, GetField, SetField, GetPropertySetProperty 열거형 멤버의 비트 조합입니다. 적합한 호출 특성을 지정해야 합니다. 예를 들어 정적 멤버를 호출하려면 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 사용하려면 먼저 클래스 Type를 가져옵니다. 에서 를 Type가져옵니다 PropertyInfo. 에서 PropertyInfo메서드를 GetValue 사용합니다.

참고

.NET Framework 2.0부터 이 메서드는 호출자가 플래그를 ReflectionPermissionFlag.RestrictedMemberAccess 사용하여 부여된 ReflectionPermission 경우 및 비공용 멤버의 권한 부여 집합이 호출자의 권한 부여 집합 또는 해당 하위 집합으로 제한되는 경우 비공용 멤버에 액세스하는 데 사용할 수 있습니다. (리플렉션에 대한 보안 고려 사항을 참조하세요.) 이 기능을 사용하려면 애플리케이션이 .NET Framework 3.5 이상을 대상으로 해야 합니다.

추가 정보

적용 대상