PropertyInfo.SetValue 方法

定義

設定指定之物件的屬性值。

多載

SetValue(Object, Object)

設定指定之物件的屬性值。

SetValue(Object, Object, Object[])

使用索引屬性的選擇性索引值,設定指定的物件的屬性值。

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

當在衍生類別中覆寫時,設定指定的物件的屬性值,此物件具有指定的繫結、索引和文化特性特定資訊。

SetValue(Object, Object)

來源:
PropertyInfo.cs
來源:
PropertyInfo.cs
來源:
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 類型不符合目標類型,或屬性是執行個體屬性但 objnull

注意:在 適用于 Windows 市集應用程式的 .NET可攜式類別庫中,改為攔截 Exception

曾不合法嘗試存取類別內的私用或保護方法。

注意:在 適用于 Windows 市集應用程式的 .NET可攜式類別庫中,改為攔截基類例外狀況 MemberAccessException

設定屬性值時發生錯誤。 InnerException 屬性指出錯誤的原因。

範例

下列範例會在 Visual Basic) 和一個實例屬性中宣告名為 Example 的類別,其中一 static 個 (Shared 。 此範例會 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 物件的屬性類型是實值型別且 valuenull ,則屬性會設定為該型別的預設值。

這是一種便利的方法,它會呼叫抽象 SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) 方法的執行時間實作,並 BindingFlags.Default 針對 BindingFlags 指定 參數、針對 BindernullObject[]null 、 和 null 指定 。 CultureInfo

若要使用 SetValue 方法,請先取得 Type 代表 類別的 物件。 從 取得 TypePropertyInfo 物件。 PropertyInfo從 物件呼叫 SetValue 方法。

注意

從 .NET Framework 2.0 開始,如果呼叫端已使用 旗標授與呼叫端,而且非公用成員的授與集限制為呼叫端的授 ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess 與集或子集,這個方法就可以用來存取非公用成員。 (請參閱 Reflection.) 的安全性考慮若要使用此功能,您的應用程式應以 .NET Framework 3.5 或更新版本為目標。

適用於

SetValue(Object, Object, Object[])

來源:
PropertyInfo.cs
來源:
PropertyInfo.cs
來源:
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 類型。

物件不符合目標類型,或屬性是執行個體屬性但 objnull

注意:在 適用于 Windows 市集應用程式的 .NET可攜式類別庫中,改為攔截 Exception

index 中的參數數目不符合索引屬性所接受的參數數目。

曾不合法嘗試存取類別內的私用或保護方法。

注意:在 適用于 Windows 市集應用程式的 .NET可攜式類別庫中,改為攔截基類例外狀況 MemberAccessException

設定屬性值時發生錯誤。 例如,為索引屬性指定的索引值超出範圍。 InnerException 屬性指出錯誤的原因。

範例

下列範例會定義名為 TestClass 的類別,其具有名為 Caption 的讀寫屬性。 它會顯示內容的 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 類別: static Visual Basic) 、實例屬性和索引實例屬性中的屬性 (Shared 。 此範例會 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 物件是實值型別且 valuenull ,則 屬性會設定為該類型的預設值。

若要判斷屬性是否已編制索引,請使用 GetIndexParameters 方法。 如果產生的陣列有 0 (零個) 元素,則屬性不會編制索引。

這是一種便利的方法,可呼叫抽象 SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) 方法的執行時間實作,並 BindingFlags.Default 針對 BindingFlags 指定 參數、 nullBinder 針對 和 null 指定 CultureInfo

若要使用 SetValue 方法,請先取得 Type 代表 類別的 物件。 從 取得 TypePropertyInfo 。 從 使用 PropertyInfoSetValue 方法。

注意

從 .NET Framework 2.0 開始,如果呼叫端已使用 旗標授與呼叫端,而且非公用成員的授與集限制為呼叫端的授 ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess 與集或子集,這個方法就可以用來存取非公用成員。 (請參閱 Reflection.) 的安全性考慮若要使用此功能,您的應用程式應以 .NET Framework 3.5 或更新版本為目標。

適用於

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

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

下列可指定引動過程屬性之列舉成員的位元組合:InvokeMethodCreateInstanceStaticGetFieldSetFieldGetPropertySetProperty。 您必須指定適當的引動過程屬性。 例如,要叫用靜態成員,就設定 Static 旗標。

binder
Binder

使用反映來啟用繫結、強制引數的類型、成員的引動過程,和擷取 MemberInfo 物件的物件。 如果 bindernull,則會使用預設繫結器。

index
Object[]

索引屬性的選擇性索引值。 非索引屬性的這個值應為 null

culture
CultureInfo

資源要當地語系化的文化特性。 如果未針對這個文化特性將資源當地語系化,則將在搜尋相符項目時持續呼叫 Parent 屬性。 如果這個值是 null,則會從 CurrentUICulture 屬性取得特定文化特性資訊。

實作

例外狀況

index 陣列未包含所需的引數類型。

-或-

找不到屬性的 set 存取子。

-或-

value 無法轉換成 PropertyType 類型。

物件不符合目標類型,或屬性是執行個體屬性但 objnull

index 中的參數數目不符合索引屬性所接受的參數數目。

曾不合法嘗試存取類別內的私用或保護方法。

設定屬性值時發生錯誤。 例如,為索引屬性指定的索引值超出範圍。 InnerException 屬性指出錯誤的原因。

備註

如果這個 PropertyInfo 物件是實值型別且 valuenull ,則 屬性會設定為該類型的預設值。

若要判斷屬性是否已編制索引,請使用 GetIndexParameters 方法。 如果產生的陣列有 0 (零個) 元素,則屬性不會編制索引。

完全信任的程式碼會忽略存取限制。 也就是說,只要程式碼完全信任,就可以透過 Reflection 存取和叫用私用建構函式、方法、欄位和屬性。

若要使用 SetValue 方法,請先取得 類別 Type 。 從 取得 TypePropertyInfo 。 從 使用 PropertyInfoSetValue 方法。

注意

從 .NET Framework 2.0 開始,如果呼叫端已使用 旗標授與呼叫端,而且非公用成員的授與集限制為呼叫端的授 ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess 與集或子集,這個方法就可以用來存取非公用成員。 (請參閱 Reflection.) 的安全性考慮若要使用此功能,您的應用程式應以 .NET Framework 3.5 或更新版本為目標。

適用於