PropertyInfo.SetValue メソッド

定義

指定されたオブジェクトのプロパティの値を設定します。

オーバーロード

SetValue(Object, Object)

指定されたオブジェクトのプロパティの値を設定します。

SetValue(Object, Object, Object[])

指定したオブジェクトのプロパティの値を設定します。インデックス プロパティの場合は、オプションでインデックス値を設定できます。

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

派生クラスでオーバーライドされると、指定したバインディング、インデックス、およびカルチャ固有の情報を含む指定されたオブジェクトのプロパティ値を設定します。

SetValue(Object, Object)

指定されたオブジェクトのプロパティの値を設定します。

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です。

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

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

注: .NET for Windows ストア アプリ または ポータブル クラス ライブラリでは、代わりに基底クラスの例外 MemberAccessExceptionをキャッチします。

プロパティ値を設定しているときにエラーが発生しました。 InnerException プロパティは、エラーの理由を示します。

次の例では、 という名前 Example のクラスを、1 つの static (Shared Visual Basic では ) と 1 つのインスタンス プロパティで宣言します。 この例では、 メソッドを 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 (ゼロ) の要素がある場合、プロパティのインデックスは作成されません。 インデックス付きプロパティの値を設定するには、 オーバーロードを SetValue(Object, Object, Object[]) 呼び出します。

この PropertyInfo オブジェクトのプロパティ型が値型で value 、 が の null場合、プロパティはその型の既定値に設定されます。

これは、抽象メソッドのランタイム実装を呼び出す便利なSetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)メソッドで、 パラメーター nullnullBinderに をBindingFlags、 に をObject[]null指定BindingFlags.Defaultします。CultureInfo

メソッドを使用するには、最初に SetValue クラスを Type 表す オブジェクトを取得します。 から、 Typeオブジェクトを PropertyInfo 取得します。 オブジェクトから、 PropertyInfo メソッドを SetValue 呼び出します。

注意

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

適用対象

SetValue(Object, Object, Object[])

指定したオブジェクトのプロパティの値を設定します。インデックス プロパティの場合は、オプションでインデックス値を設定できます。

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です。

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

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

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

注: .NET for Windows ストア アプリ または ポータブル クラス ライブラリでは、代わりに基底クラスの例外 MemberAccessExceptionをキャッチします。

プロパティ値を設定しているときにエラーが発生しました。 たとえば、インデックス付きプロパティで指定されたインデックス値が範囲外です。 InnerException プロパティは、エラーの理由を示します。

次の例では、 という名前 TestClass の読み取り/書き込みプロパティを持つ という名前 Captionのクラスを定義します。 プロパティの既定値を表示し、 メソッドをCaptionSetValue呼び出してプロパティ値を変更し、結果を表示します。

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.

プロパティはパラメーター配列ではないので Captionindex 引数は であることに null注意してください。

次の例では、プロパティ (Shared Visual Basic の場合)、インスタンス プロパティ、インデックス付きインスタンス プロパティの 3 つのプロパティstaticを持つ という名前Exampleのクラスを宣言します。 この例では、 メソッドを SetValue 使用してプロパティの既定値を変更し、元の値と最終値を表示します。

リフレクションを使用してインデックス付きインスタンス プロパティを検索するために使用される名前は、言語とプロパティに適用される属性によって異なります。

  • Visual Basic では、プロパティ名は常にリフレクションを使用してプロパティを検索するために使用されます。 キーワードを Default 使用すると、プロパティを既定のインデックス付きプロパティにすることができます。その場合、この例のように、プロパティにアクセスするときに名前を省略できます。 プロパティ名を使用することもできます。

  • C# では、インデックス付きインスタンス プロパティはインデクサーと呼ばれる既定のプロパティであり、コード内の プロパティにアクセスするときに名前は使用されません。 既定では、プロパティの名前は です 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 オブジェクトが値型で value 、 が の null場合、プロパティはその型の既定値に設定されます。

プロパティにインデックスが付いているかどうかを確認するには、 メソッドを使用します GetIndexParameters 。 結果の配列に 0 (ゼロ) の要素がある場合、プロパティのインデックスは作成されません。

これは、抽象メソッドのランタイム実装を呼び出す便利なSetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)メソッドで、 パラメーターnullに を、、 に BindingFlagsnullBinder指定BindingFlags.DefaultしますCultureInfo

メソッドを使用するには、最初に SetValue クラスを Type 表す オブジェクトを取得します。 から、 Typeを取得します PropertyInfo。 から、 PropertyInfoメソッドを使用します SetValue

注意

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

適用対象

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

派生クラスでオーバーライドされると、指定したバインディング、インデックス、およびカルチャ固有の情報を含む指定されたオブジェクトのプロパティ値を設定します。

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

呼び出し属性を指定する次の列挙型メンバーのビットごとの組み合わせ: InvokeMethodCreateInstanceStaticGetFieldSetFieldGetProperty または SetProperty。 適切な呼び出し属性を指定する必要があります。 たとえば、静的メンバーを呼び出すには、Static フラグを設定します。

binder
Binder

バインディング、引数型の強制変換、メンバーの呼び出し、およびリフレクションを使用した MemberInfo オブジェクトの取得を有効にするオブジェクト。 bindernull の場合は、既定のバインダーが使用されます。

index
Object[]

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

culture
CultureInfo

リソースのローカライズ対象のカルチャ。 リソースがこのカルチャ用にローカライズされていない場合は、一致する対象を検索するために Parent プロパティが連続して呼び出されます。 この値が null の場合は、CurrentUICulture プロパティからカルチャ固有の情報が習得されます。

実装

例外

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

または

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

または

valuePropertyType の型に変換することはできません。

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

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

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

プロパティ値を設定しているときにエラーが発生しました。 たとえば、インデックス付きプロパティで指定されたインデックス値が範囲外です。 InnerException プロパティは、エラーの理由を示します。

注釈

この PropertyInfo オブジェクトが値型で value 、 が の null場合、プロパティはその型の既定値に設定されます。

プロパティにインデックスが付いているかどうかを確認するには、 メソッドを使用します GetIndexParameters 。 結果の配列に 0 (ゼロ) の要素がある場合、プロパティのインデックスは作成されません。

完全に信頼されたコードでは、アクセス制限は無視されます。 つまり、プライベート コンストラクター、メソッド、フィールド、プロパティにアクセスし、コードが完全に信頼されるたびに Reflection を介して呼び出すことができます。

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

注意

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

適用対象