다음을 통해 공유


PropertyInfo.SetValue 메서드

정의

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

오버로드

Name Description
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
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 접근자를 찾을 수 없습니다.

-또는-

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

형식 obj 이 대상 형식과 일치하지 않거나 속성이 인스턴스 속성이지만 obj .null

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

속성 값을 설정하는 동안 오류가 발생했습니다. 이 속성은 InnerException 오류의 원인을 나타냅니다.

예제

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

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

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

이 메서드는 추상 SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) 메서드의 런타임 구현을 호출하고 매개 변수, forBindingFlags, null for Bindernullnull forObject[]CultureInfo를 지정하는 BindingFlags.Default 편리한 메서드입니다.

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

메모

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

적용 대상

SetValue(Object, Object, Object[])

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
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 접근자를 찾을 수 없습니다.

-또는-

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

개체가 대상 형식과 일치하지 않거나 속성이 인스턴스 속성이지만 obj .null

매개 index 변수의 수는 인덱싱된 속성이 취하는 매개 변수 수와 일치하지 않습니다.

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

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

예제

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

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.

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

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

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

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

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) 메서드의 런타임 구현을 호출하고 매개 변수, for 및 null for nullBinderCultureInfo를 지정하는 BindingFlags.DefaultBindingFlags 편리한 메서드입니다.

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

메모

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

적용 대상

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

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

호출 특성을 InvokeMethodSetFieldSetPropertyCreateInstanceStaticGetFieldGetProperty지정하는 다음 열거형 멤버의 비트 조합입니다. 적절한 호출 특성을 지정해야 합니다. 예를 들어 정적 멤버를 호출하려면 플래그를 Static 설정합니다.

binder
Binder

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

index
Object[]

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

culture
CultureInfo

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

구현

예외

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

-또는-

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

-또는-

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

개체가 대상 형식과 일치하지 않거나 속성이 인스턴스 속성이지만 obj .null

매개 index 변수의 수는 인덱싱된 속성이 취하는 매개 변수 수와 일치하지 않습니다.

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

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

설명

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

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

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

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

메모

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

적용 대상