PropertyInfo.SetValue 메서드

정의

지정된 개체에 대한 속성 값을 설정합니다.

오버로드

SetValue(Object, Object)

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

SetValue(Object, Object, Object[])

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

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

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

SetValue(Object, Object)

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

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

public:
 void SetValue(System::Object ^ obj, System::Object ^ value);
public void SetValue (object obj, object value);
public void SetValue (object? obj, object? value);
member this.SetValue : obj * obj -> unit
Public Sub SetValue (obj As Object, value As Object)

매개 변수

obj
Object

속성 값이 설정될 개체입니다.

value
Object

새 속성 값입니다.

예외

속성의 set 접근자를 찾을 수 없습니다.

또는

valuePropertyType의 형식으로 변환할 수 없습니다.

obj의 형식이 대상 형식과 일치하지 않거나 속성이 인스턴스 속성이지만 objnull입니다.

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

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

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

속성 값을 설정할 때 오류가 발생했습니다. InnerException 속성은 오류가 발생한 원인을 나타냅니다.

예제

다음 예제에서는 라는 클래스 Example 를 선언 합니다( staticShared Visual Basic에서는) 및 하나의 instance 속성입니다. 이 예제에서는 메서드를 SetValue(Object, Object) 사용하여 원래 속성 값을 변경하고 원래 및 최종 값을 표시합니다.

using namespace System;
using namespace System::Reflection;

ref class Example
{
private:
    int static _sharedProperty = 41;
    int _instanceProperty;


public:
    Example()
    {
        _instanceProperty = 42;
    };

    static property int SharedProperty
    {
        int get() { return _sharedProperty; }
        void set(int value) { _sharedProperty = value; }
    };

    property int InstanceProperty 
    {
        int get() { return _instanceProperty; }
        void set(int value) { _instanceProperty = value; }
    };

};

void main()
{
    Console::WriteLine("Initial value of static property: {0}",
                       Example::SharedProperty);

    PropertyInfo^ piShared = 
        Example::typeid->GetProperty("SharedProperty");
    piShared->SetValue(nullptr, 76, nullptr);
                 
    Console::WriteLine("New value of static property: {0}",
                       Example::SharedProperty);


    Example^ exam = gcnew Example();

    Console::WriteLine("\nInitial value of instance property: {0}", 
            exam->InstanceProperty);

    PropertyInfo^ piInstance = 
        Example::typeid->GetProperty("InstanceProperty");
    piInstance->SetValue(exam, 37, nullptr);
                 
    Console::WriteLine("New value of instance property: {0}",
                       exam->InstanceProperty);
};

/* The example displays the following output:
      Initial value of static property: 41
      New value of static property: 76

      Initial value of instance property: 42
      New value of instance property: 37
 */
using System;
using System.Reflection;

class Example
{
    private static int _staticProperty = 41;
    private int _instanceProperty = 42;

    // Declare a public static property.
    public static int StaticProperty
    {
        get { return _staticProperty; }
        set { _staticProperty = value; }
    }

    // Declare a public instance property.
    public int InstanceProperty
    {
        get { return _instanceProperty; }
        set { _instanceProperty = value; }
    }

    public static void Main()
    {
        Console.WriteLine("Initial value of static property: {0}",
            Example.StaticProperty);

        // Get a type object that represents the Example type.
        Type examType = typeof(Example);

        // Change the static property value.
        PropertyInfo piShared = examType.GetProperty("StaticProperty");
        piShared.SetValue(null, 76);

        Console.WriteLine("New value of static property: {0}",
                          Example.StaticProperty);

        // Create an instance of the Example class.
        Example exam = new Example();

        Console.WriteLine("\nInitial value of instance property: {0}",
                          exam.InstanceProperty);

        // Change the instance property value.
        PropertyInfo piInstance = examType.GetProperty("InstanceProperty");
        piInstance.SetValue(exam, 37);

        Console.WriteLine("New value of instance property: {0}",
                          exam.InstanceProperty);
    }
}
// The example displays the following output:
//       Initial value of static property: 41
//       New value of static property: 76
//
//       Initial value of instance property: 42
//       New value of instance property: 37
Imports System.Reflection

Class Example
    Private Shared _sharedProperty As Integer = 41
    Private _instanceProperty As Integer = 42

    ' Declare a public static (shared) property.
    Public Shared Property SharedProperty As Integer
        Get 
            Return _sharedProperty
        End Get
        Set
            _sharedProperty = Value
        End Set
    End Property

    ' Declare a public instance property.
    Public Property InstanceProperty As Integer
        Get 
            Return _instanceProperty
        End Get
        Set
            _instanceProperty = Value
        End Set
    End Property

    Public Shared Sub Main()
        Console.WriteLine("Initial value of shared property: {0}",
                          Example.SharedProperty)

        ' Get a type object that represents the Example type.
        Dim examType As Type = GetType(Example)
        
        ' Change the static (shared) property value.
        Dim piShared As PropertyInfo = examType.GetProperty("SharedProperty")
        piShared.SetValue(Nothing, 76)
                 
        Console.WriteLine("New value of shared property: {0}",
                          Example.SharedProperty)
        Console.WriteLine()

        ' Create an instance of the Example class.
        Dim exam As New Example

        Console.WriteLine("Initial value of instance property: {0}",
                          exam.InstanceProperty)

        ' Change the instance property value.
        Dim piInstance As PropertyInfo = examType.GetProperty("InstanceProperty")
        piInstance.SetValue(exam, 37)
                 
        Console.WriteLine("New value of instance property: {0}", _
                          exam.InstanceProperty)
    End Sub
End Class
' The example displays the following output:
'       Initial value of shared property: 41
'       New value of shared property: 76
'
'       Initial value of instance property: 42
'       New value of instance property: 37

설명

SetValue(Object, Object) 오버로드는 인덱싱되지 않은 속성의 값을 설정합니다. 속성이 인덱싱되는지 여부를 확인하려면 메서드를 호출합니다 GetIndexParameters . 결과 배열에 0(0) 요소가 있으면 속성이 인덱싱되지 않습니다. 인덱싱된 속성의 값을 설정하려면 오버로드를 호출합니다 SetValue(Object, Object, Object[]) .

이 개체의 속성 형식이 값 형식이고 valuenullPropertyInfo 면 속성이 해당 형식의 기본값으로 설정됩니다.

이 메서드는 추상 SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) 메서드의 런타임 구현을 호출하는 BindingFlags.DefaultBindingFlags 편리한 메서드로, 매개 변수, nullBindernullnull 에 대해 Object[]CultureInfo를 지정합니다.

메서드를 SetValue 사용하려면 먼저 클래스를 Type 나타내는 개체를 가져옵니다. Type에서 개체를 PropertyInfo 가져옵니다. 개체에서 PropertyInfo 메서드를 호출합니다 SetValue .

참고

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

적용 대상

SetValue(Object, Object, Object[])

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

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

public:
 virtual void SetValue(System::Object ^ obj, System::Object ^ value, cli::array <System::Object ^> ^ index);
public virtual void SetValue (object obj, object value, object[] index);
public virtual void SetValue (object? obj, object? value, object?[]? index);
abstract member SetValue : obj * obj * obj[] -> unit
override this.SetValue : obj * obj * obj[] -> unit
Public Overridable Sub SetValue (obj As Object, value As Object, index As Object())

매개 변수

obj
Object

속성 값이 설정될 개체입니다.

value
Object

새 속성 값입니다.

index
Object[]

인덱싱된 속성에 대한 선택적 인덱스 값입니다. 인덱싱되지 않은 속성에 대해서는 이 값이 null이어야 합니다.

구현

예외

index 배열에 필요한 인수의 형식이 포함되어 있지 않습니다.

또는

속성의 set 접근자를 찾을 수 없습니다.

또는

valuePropertyType의 형식으로 변환할 수 없습니다.

개체가 대상 형식과 일치하지 않거나 속성이 인스턴스 속성이지만 objnull입니다.

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

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

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

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

속성 값을 설정할 때 오류가 발생했습니다. 예를 들어, 인덱싱된 속성에 대해 지정된 인덱스 값이 범위를 벗어났습니다. InnerException 속성은 오류가 발생한 원인을 나타냅니다.

예제

다음 예제에서는 라는 Caption읽기-쓰기 속성이 있는 라는 TestClass 클래스를 정의합니다. 속성의 기본값을 Caption 표시하고, 메서드를 SetValue 호출하여 속성 값을 변경하고, 결과를 표시합니다.

using namespace System;
using namespace System::Reflection;

// Define a property.
public ref class TestClass
{
private:
   String^ caption;

public:
   TestClass()
   {
      caption = "A Default caption";
   }


   property String^ Caption 
   {
      String^ get()
      {
         return caption;
      }

      void set( String^ value )
      {
         if ( caption != value )
         {
            caption = value;
         }
      }

   }

};

int main()
{
   TestClass^ t = gcnew TestClass;
   
   // Get the type and PropertyInfo.
   Type^ myType = t->GetType();
   PropertyInfo^ pinfo = myType->GetProperty( "Caption" );
   
   // Display the property value, using the GetValue method.
   Console::WriteLine( "\nGetValue: {0}", pinfo->GetValue( t, nullptr ) );
   
   // Use the SetValue method to change the caption.
   pinfo->SetValue( t, "This caption has been changed.", nullptr );
   
   // Display the caption again.
   Console::WriteLine( "GetValue: {0}", pinfo->GetValue( t, nullptr ) );
   Console::WriteLine( "\nPress the Enter key to continue." );
   Console::ReadLine();
   return 0;
}

/*
This example produces the following output:
 
GetValue: A Default caption
GetValue: This caption has been changed

Press the Enter key to continue.
*/
using System;
using System.Reflection;

// Define a class with a property.
public class TestClass
{
    private string caption = "A Default caption";
    public string Caption
    {
        get { return caption; }
        set
        {
            if (caption != value)
            {
                caption = value;
            }
        }
    }
}

class TestPropertyInfo
{
    public static void Main()
    {
        TestClass t = new TestClass();

        // Get the type and PropertyInfo.
        Type myType = t.GetType();
        PropertyInfo pinfo = myType.GetProperty("Caption");

        // Display the property value, using the GetValue method.
        Console.WriteLine("\nGetValue: " + pinfo.GetValue(t, null));

        // Use the SetValue method to change the caption.
        pinfo.SetValue(t, "This caption has been changed.", null);

        //  Display the caption again.
        Console.WriteLine("GetValue: " + pinfo.GetValue(t, null));

        Console.WriteLine("\nPress the Enter key to continue.");
        Console.ReadLine();
    }
}

/*
This example produces the following output:

GetValue: A Default caption
GetValue: This caption has been changed

Press the Enter key to continue.
*/
Imports System.Reflection

' Define a class with a property.
Public Class TestClass
    Private myCaption As String = "A Default caption"

    Public Property Caption() As String
        Get
            Return myCaption
        End Get
        Set
            If myCaption <> value Then myCaption = value
        End Set
    End Property
End Class

Public Class TestPropertyInfo
    Public Shared Sub Main()
        Dim t As New TestClass()

        ' Get the type and PropertyInfo.
        Dim myType As Type = t.GetType()
        Dim pinfo As PropertyInfo = myType.GetProperty("Caption")

        ' Display the property value, using the GetValue method.
        Console.WriteLine(vbCrLf & "GetValue: " & pinfo.GetValue(t, Nothing))

        ' Use the SetValue method to change the caption.
        pinfo.SetValue(t, "This caption has been changed.", Nothing)

        ' Display the caption again.
        Console.WriteLine("GetValue: " & pinfo.GetValue(t, Nothing))

        Console.WriteLine(vbCrLf & "Press the Enter key to continue.")
        Console.ReadLine()
    End Sub
End Class

' This example produces the following output:
' 
'GetValue: A Default caption
'GetValue: This caption has been changed
'
'Press the Enter key to continue.

속성이 Caption 매개 변수 배열이 아니므로 인수는 index 입니다 null.

다음 예제에서는 세 가지 속성으로 라는 Example 클래스를 선언합니다. 속성(Shared Visual Basic의 경우), instance 속성 및 인덱싱된 instance 속성 static 입니다. 이 예제에서는 메서드를 SetValue 사용하여 속성의 기본값을 변경하고 원래 값과 최종 값을 표시합니다.

리플렉션이 있는 인덱싱된 instance 속성을 검색하는 데 사용되는 이름은 언어 및 속성에 적용된 특성에 따라 다릅니다.

  • Visual Basic에서 속성 이름은 항상 리플렉션을 사용하여 속성을 검색하는 데 사용됩니다. 키워드(keyword) 사용하여 Default 속성을 기본 인덱싱된 속성으로 만들 수 있습니다. 이 경우 이 예제와 같이 속성에 액세스할 때 이름을 생략할 수 있습니다. 속성 이름을 사용할 수도 있습니다.

  • C#에서 인덱싱된 instance 속성은 인덱서라는 기본 속성이며 코드에서 속성에 액세스할 때 이름은 사용되지 않습니다. 기본적으로 속성의 이름은 이며 Item리플렉션이 있는 속성을 검색할 때 해당 이름을 사용해야 합니다. 특성을 사용하여 IndexerNameAttribute 인덱서에 다른 이름을 지정할 수 있습니다. 이 예제에서 이름은 IndexedInstanceProperty입니다.

  • C++ default 에서 지정자를 사용하여 인덱싱된 속성을 기본 인덱싱된 속성(클래스 인덱서)으로 만들 수 있습니다. 이 경우 기본적으로 속성의 이름은 이며 Item이 예제와 같이 리플렉션이 있는 속성을 검색할 때 해당 이름을 사용해야 합니다. 특성을 사용하여 IndexerNameAttribute 클래스 인덱서에 리플렉션에서 다른 이름을 지정할 수 있지만 해당 이름을 사용하여 코드의 속성에 액세스할 수는 없습니다. 클래스 인덱서가 아닌 인덱싱된 속성은 코드와 리플렉션 모두에서 해당 이름을 사용하여 액세스합니다.

using namespace System;
using namespace System::Reflection;
using namespace System::Collections::Generic;

ref class Example
{
private:
    int static _sharedProperty = 41;
    int _instanceProperty;
    Dictionary<int, String^>^ _indexedInstanceProperty;

public:
    Example()
    {
        _instanceProperty = 42;
        _indexedInstanceProperty = gcnew Dictionary<int, String^>();
    };

    static property int SharedProperty
    {
        int get() { return _sharedProperty; }
        void set(int value) { _sharedProperty = value; }
    };

    property int InstanceProperty 
    {
        int get() { return _instanceProperty; }
        void set(int value) { _instanceProperty = value; }
    };

    // By default, the name of the default indexed property (class 
    // indexer) is Item, and that name must be used to search for the 
    // property with reflection. The property can be given a different
    // name by using the IndexerNameAttribute attribute.
    property String^ default[int]
    { 
        String^ get(int key) 
        { 
            String^ returnValue;
            if (_indexedInstanceProperty->TryGetValue(key, returnValue))
            {
                return returnValue;
            }
            else
            {
                return nullptr;
            }
        }
        void set(int key, String^ value)
        {
            if (value == nullptr)
            {
                throw gcnew ArgumentNullException( 
                    "IndexedInstanceProperty value can be an empty string, but it cannot be null.");
            }
            else
            {
                if (_indexedInstanceProperty->ContainsKey(key))
                {
                    _indexedInstanceProperty[key] = value;
                }
                else
                {
                    _indexedInstanceProperty->Add(key, value);
                }
            }
        }
    };
};

void main()
{
    Console::WriteLine("Initial value of class-level property: {0}", 
        Example::SharedProperty);

    PropertyInfo^ piShared = 
        Example::typeid->GetProperty("SharedProperty");
    piShared->SetValue(nullptr, 76, nullptr);
                 
    Console::WriteLine("Final value of class-level property: {0}", 
        Example::SharedProperty);


    Example^ exam = gcnew Example();

    Console::WriteLine("\nInitial value of instance property: {0}", 
            exam->InstanceProperty);

    PropertyInfo^ piInstance = 
        Example::typeid->GetProperty("InstanceProperty");
    piInstance->SetValue(exam, 37, nullptr);
                 
    Console::WriteLine("Final value of instance property: {0}", 
        exam->InstanceProperty);


    exam[17] = "String number 17";
    exam[46] = "String number 46";
    exam[9] = "String number 9";

    Console::WriteLine(
        "\nInitial value of indexed instance property(17): '{0}'", 
        exam[17]);

    // By default, the name of the default indexed property (class 
    // indexer) is Item, and that name must be used to search for the 
    // property with reflection. The property can be given a different
    // name by using the IndexerNameAttribute attribute.
    PropertyInfo^ piIndexedInstance =
        Example::typeid->GetProperty("Item");
    piIndexedInstance->SetValue(
            exam, 
            "New value for string number 17", 
            gcnew array<Object^> { 17 });
                 
    Console::WriteLine("Final value of indexed instance property(17): '{0}'", 
        exam[17]);
};

/* This example produces the following output:

Initial value of class-level property: 41
Final value of class-level property: 76

Initial value of instance property: 42
Final value of instance property: 37

Initial value of indexed instance property(17): 'String number 17'
Final value of indexed instance property(17): 'New value for string number 17'
 */
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

class Example
{
    private static int _staticProperty = 41;
    public static int StaticProperty
    {
        get
        {
            return _staticProperty;
        }
        set
        {
            _staticProperty = value;
        }
    }

    private int _instanceProperty = 42;
    public int InstanceProperty
    {
        get
        {
            return _instanceProperty;
        }
        set
        {
            _instanceProperty = value;
        }
    }

    private Dictionary<int, string> _indexedInstanceProperty =
        new Dictionary<int, string>();
    // By default, the indexer is named Item, and that name must be used
    // to search for the property. In this example, the indexer is given
    // a different name by using the IndexerNameAttribute attribute.
    [IndexerNameAttribute("IndexedInstanceProperty")]
    public string this[int key]
    {
        get
        {
            string returnValue = null;
            if (_indexedInstanceProperty.TryGetValue(key, out returnValue))
            {
                return returnValue;
            }
            else
            {
                return null;
            }
        }
        set
        {
            if (value == null)
            {
                throw new ArgumentNullException("IndexedInstanceProperty value can be an empty string, but it cannot be null.");
            }
            else
            {
                if (_indexedInstanceProperty.ContainsKey(key))
                {
                    _indexedInstanceProperty[key] = value;
                }
                else
                {
                    _indexedInstanceProperty.Add(key, value);
                }
            }
        }
    }

    public static void Main()
    {
        Console.WriteLine("Initial value of class-level property: {0}",
            Example.StaticProperty);

        PropertyInfo piShared = typeof(Example).GetProperty("StaticProperty");
        piShared.SetValue(null, 76, null);

        Console.WriteLine("Final value of class-level property: {0}",
            Example.StaticProperty);

        Example exam = new Example();

        Console.WriteLine("\nInitial value of instance property: {0}",
            exam.InstanceProperty);

        PropertyInfo piInstance =
            typeof(Example).GetProperty("InstanceProperty");
        piInstance.SetValue(exam, 37, null);

        Console.WriteLine("Final value of instance property: {0}",
            exam.InstanceProperty);

        exam[17] = "String number 17";
        exam[46] = "String number 46";
        exam[9] = "String number 9";

        Console.WriteLine(
            "\nInitial value of indexed instance property(17): '{0}'",
            exam[17]);

        // By default, the indexer is named Item, and that name must be used
        // to search for the property. In this example, the indexer is given
        // a different name by using the IndexerNameAttribute attribute.
        PropertyInfo piIndexedInstance =
            typeof(Example).GetProperty("IndexedInstanceProperty");
        piIndexedInstance.SetValue(
            exam,
            "New value for string number 17",
            new object[] { (int) 17 });

        Console.WriteLine(
            "Final value of indexed instance property(17): '{0}'",
            exam[17]);
    }
}

/* This example produces the following output:

Initial value of class-level property: 41
Final value of class-level property: 76

Initial value of instance property: 42
Final value of instance property: 37

Initial value of indexed instance property(17): 'String number 17'
Final value of indexed instance property(17): 'New value for string number 17'
 */
Imports System.Reflection
Imports System.Collections.Generic

Class Example

    Private Shared _sharedProperty As Integer = 41
    Public Shared Property SharedProperty As Integer
        Get 
            Return _sharedProperty
        End Get
        Set
            _sharedProperty = Value
        End Set
    End Property

    Private _instanceProperty As Integer = 42
    Public Property InstanceProperty As Integer
        Get 
            Return _instanceProperty
        End Get
        Set
            _instanceProperty = Value
        End Set
    End Property

    Private _indexedInstanceProperty As New Dictionary(Of Integer, String)
    Default Public Property IndexedInstanceProperty(ByVal key As Integer) As String
        Get 
            Dim returnValue As String = Nothing
            If _indexedInstanceProperty.TryGetValue(key, returnValue) Then
                Return returnValue
            Else
                Return Nothing
            End If
        End Get
        Set
            If Value Is Nothing Then
                Throw New ArgumentNullException( _
                    "IndexedInstanceProperty value can be an empty string, but it cannot be Nothing.")
            Else
                If _indexedInstanceProperty.ContainsKey(key) Then
                    _indexedInstanceProperty(key) = Value
                Else
                    _indexedInstanceProperty.Add(key, Value)
                End If
            End If
        End Set
    End Property


    Shared Sub Main()

        Console.WriteLine("Initial value of class-level property: {0}", _
            Example.SharedProperty)

        Dim piShared As PropertyInfo = _
            GetType(Example).GetProperty("SharedProperty")
        piShared.SetValue( _
            Nothing, _
            76, _
            Nothing)
                 
        Console.WriteLine("Final value of class-level property: {0}", _
            Example.SharedProperty)


        Dim exam As New Example

        Console.WriteLine(vbCrLf & _
            "Initial value of instance property: {0}", _
            exam.InstanceProperty)

        Dim piInstance As PropertyInfo = _
            GetType(Example).GetProperty("InstanceProperty")
        piInstance.SetValue( _
            exam, _
            37, _
            Nothing)
                 
        Console.WriteLine("Final value of instance property: {0}", _
            exam.InstanceProperty)


        exam(17) = "String number 17"
        exam(46) = "String number 46"
        ' In Visual Basic, a default indexed property can also be referred
        ' to by name.
        exam.IndexedInstanceProperty(9) = "String number 9"

        Console.WriteLine(vbCrLf & _
            "Initial value of indexed instance property(17): '{0}'", _
            exam(17))

        Dim piIndexedInstance As PropertyInfo = _
            GetType(Example).GetProperty("IndexedInstanceProperty")
        piIndexedInstance.SetValue( _
            exam, _
            "New value for string number 17", _
            New Object() { CType(17, Integer) })
                 
        Console.WriteLine("Final value of indexed instance property(17): '{0}'", _
            exam(17))
        
    End Sub
End Class

' This example produces the following output:
'
'Initial value of class-level property: 41
'Final value of class-level property: 76
'
'Initial value of instance property: 42
'Final value of instance property: 37
'
'Initial value of indexed instance property(17): 'String number 17'
'Final value of indexed instance property(17): 'New value for string number 17'

설명

PropertyInfo 개체가 값 형식이고 valuenull면 속성이 해당 형식의 기본값으로 설정됩니다.

속성이 인덱싱되는지 여부를 확인하려면 메서드를 GetIndexParameters 사용합니다. 결과 배열에 0(0) 요소가 있으면 속성이 인덱싱되지 않습니다.

이 메서드는 추상 SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) 메서드의 런타임 구현을 호출하는 BindingFlags.Default 편리한 메서드로, 매개 변수, null , BindingFlagsnull 에 대해 BinderCultureInfo를 지정합니다.

메서드를 SetValue 사용하려면 먼저 클래스를 Type 나타내는 개체를 가져옵니다. 에서 를 Type가져옵니다 PropertyInfo. 에서 PropertyInfo메서드를 SetValue 사용합니다.

참고

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

적용 대상

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

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

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

public:
 abstract void SetValue(System::Object ^ obj, System::Object ^ value, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ index, System::Globalization::CultureInfo ^ culture);
public abstract void SetValue (object? obj, object? value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, object?[]? index, System.Globalization.CultureInfo? culture);
public abstract void SetValue (object obj, object value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] index, System.Globalization.CultureInfo culture);
abstract member SetValue : obj * obj * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> unit
Public MustOverride Sub SetValue (obj As Object, value As Object, invokeAttr As BindingFlags, binder As Binder, index As Object(), culture As CultureInfo)

매개 변수

obj
Object

속성 값이 설정될 개체입니다.

value
Object

새 속성 값입니다.

invokeAttr
BindingFlags

호출 특성을 지정하는 InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty 또는 SetProperty 열거형 멤버의 비트 조합입니다. 적합한 호출 특성을 지정해야 합니다. 예를 들어 정적 멤버를 호출하려면 Static 플래그를 설정합니다.

binder
Binder

리플렉션을 통해 바인딩, 인수 형식의 강제 변환, 멤버 호출 및 MemberInfo 개체 검색을 사용할 수 있도록 하는 개체입니다. bindernull이면 기본 바인더가 사용됩니다.

index
Object[]

인덱싱된 속성에 대한 선택적 인덱스 값입니다. 인덱싱되지 않은 속성에 대해서는 이 값이 null이어야 합니다.

culture
CultureInfo

리소스를 지역화할 문화권입니다. 리소스가 이 문화권에 대해 지역화되지 않으면 Parent 속성이 연속적으로 호출되어 일치하는 문화권 정보를 검색합니다. 이 값이 null이면 CurrentUICulture 속성에서 문화권별 정보를 가져옵니다.

구현

예외

index 배열에 필요한 인수의 형식이 포함되어 있지 않습니다.

또는

속성의 set 접근자를 찾을 수 없습니다.

또는

valuePropertyType의 형식으로 변환할 수 없습니다.

개체가 대상 형식과 일치하지 않거나 속성이 인스턴스 속성이지만 objnull입니다.

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

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

속성 값을 설정할 때 오류가 발생했습니다. 예를 들어, 인덱싱된 속성에 대해 지정된 인덱스 값이 범위를 벗어났습니다. InnerException 속성은 오류가 발생한 원인을 나타냅니다.

설명

PropertyInfo 개체가 값 형식이고 valuenull면 속성이 해당 형식의 기본값으로 설정됩니다.

속성이 인덱싱되는지 여부를 확인하려면 메서드를 GetIndexParameters 사용합니다. 결과 배열에 0개 요소가 있으면 속성이 인덱싱되지 않습니다.

완전히 신뢰할 수 있는 코드에 대한 액세스 제한은 무시됩니다. 즉, 코드를 완전히 신뢰할 때마다 리플렉션을 통해 프라이빗 생성자, 메서드, 필드 및 속성에 액세스하고 호출할 수 있습니다.

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

참고

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

적용 대상