PropertyInfo.SetValue 方法

定義

設定指定物件的屬性值。

多載

名稱 Description
SetValue(Object, Object)

設定指定物件的屬性值。

SetValue(Object, Object, Object[])

設定指定物件的屬性值,並可選地為索引屬性設定索引值。

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

當在派生類別中覆寫時,會設定指定物件的屬性值,該物件包含指定的綁定、索引及文化特定資訊。

SetValue(Object, Object)

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

曾有非法嘗試存取類別內的私有或受保護方法。

設定房產價值時發生錯誤。 該 InnerException 性質顯示錯誤的原因。

範例

以下範例宣告一個名為 Example 的類別,包含一個 static(Visual Basic 中為 Shared)及一個實例屬性。 範例中使用了 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)個元素,則該性質不會被索引。 要設定索引屬性的值,請呼叫 overload SetValue(Object, Object, Object[])

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

這是一種方便方法,呼叫抽象SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)方法的執行時實作,對參數指定BindingFlags.DefaultBinderBindingFlagsnull為 ,對 ,nullObject[],對 ,nullCultureInfo對 。

使用這個 SetValue 方法時,首先取得 Type 一個代表該類別的物件。 從 Type中取得 PropertyInfo 該物件。 從物件 PropertyInfo 呼叫方法 SetValue

備註

若呼叫者已獲得ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess該旗標,且非公開成員的授權集限制於呼叫者的授權集或其子集,此方法可用來存取非公開成員。 (參見 安全考量 以促進反思)要使用此功能,您的應用程式應針對 .NET Framework 3.5 或更新版本。

適用於

SetValue(Object, Object, Object[])

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

中參數 index 的數量與索引性質所採用的參數數不相符。

曾有非法嘗試存取類別內的私有或受保護方法。

設定房產價值時發生錯誤。 例如,某個索引屬性指定的索引值超出範圍。 該 InnerException 性質顯示錯誤的原因。

範例

以下範例定義了一個名為 TestClass 的類別,其讀取-寫入屬性名為 Caption。 它會顯示屬性的 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 不是參數陣列,參數 indexnull

以下範例宣告了一個名為 Example 的類別,具有三個屬性:static 屬性(Visual Basic 中的 Shared)、實例性質,以及索引實例性質。 範例中使用該 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)方法的執行時實作,參數指定BindingFlags.DefaultBindingFlags參數、nullBindernullCultureInfo和 。

使用這個 SetValue 方法時,首先取得 Type 一個代表該類別的物件。 從 Type中取得 PropertyInfo。 從 , PropertyInfo使用該 SetValue 方法。

備註

在 .NET 框架中,若呼叫者已獲得帶有 ReflectionPermissionFlag.RestrictedMemberAccess 標誌的 ReflectionPermission,且非公開會員的授權集限制於呼叫者的授權集或其子集,此方法可用於存取非公開會員。 (參見 安全考量 以促進反思)要使用此功能,您的應用程式應針對 .NET Framework 3.5 或更新版本。

適用於

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

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

以下列舉成員的位元組合,指定呼叫屬性:InvokeMethodCreateInstanceStaticSetFieldGetFieldGetProperty, , , 或 。SetProperty 你必須指定合適的調用屬性。 例如,要呼叫靜態成員,設定 旗 Static 標。

binder
Binder

一個能夠約束、強制參數類型、調用成員,以及透過反思檢索 MemberInfo 物件的物件。 若 bindernull則使用預設的綁定器。

index
Object[]

索引屬性可選的索引值。 這個值應該用於 null 非索引屬性。

culture
CultureInfo

資源所屬的文化要在地化。 若該資源非本地化於此文化, Parent 該物業將被依序撥打尋找匹配。 若此值為 null,則該屬性可取得 CurrentUICulture 文化特有資訊。

實作

例外狀況

index 列中不包含所需的參數類型。

-或-

該物業 set 的配件未被找到。

-或-

value 無法轉換為 的類型 PropertyType

物件與目標類型不符,或屬性是實例屬性但 objnull

中參數 index 的數量與索引性質所採用的參數數不相符。

曾有非法嘗試存取類別內的私有或受保護方法。

設定房產價值時發生錯誤。 例如,某個索引屬性指定的索引值超出範圍。 該 InnerException 性質顯示錯誤的原因。

備註

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

要判斷某個屬性是否被索引,請使用以下 GetIndexParameters 方法。 若產生的陣列有 0(0)個元素,則該性質不會被索引。

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

使用此 SetValue 方法,首先取得類別 Type。 從 Type中取得 PropertyInfo。 從 , PropertyInfo使用該 SetValue 方法。

備註

若呼叫者已獲得ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess該旗標,且非公開成員的授權集限制於呼叫者的授權集或其子集,此方法可用來存取非公開成員。 (參見 安全考量 以促進反思)要使用此功能,您的應用程式應針對 .NET Framework 3.5 或更新版本。

適用於