通过


PropertyInfo.SetValue 方法

定义

设置指定对象的属性值。

重载

名称 说明
SetValue(Object, Object)

设置指定对象的属性值。

SetValue(Object, Object, Object[])

使用索引属性的可选索引值设置指定对象的属性值。

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

在派生类中重写时,为具有指定绑定、索引和区域性特定信息的指定对象设置属性值。

SetValue(Object, Object)

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
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 与目标类型不匹配,或者属性是实例属性,但 objnull

尝试在类中非法访问私有或受保护的方法。

设置属性值时出错。 该 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(零)个元素,则不会为该属性编制索引。 若要设置索引属性的值,请调用 SetValue(Object, Object, Object[]) 重载。

如果此PropertyInfo对象的属性类型是值类型,valuenull则此属性将设置为该类型的默认值。

这是一种便捷的方法,用于调用抽象SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)方法的运行时实现,BindingFlags.DefaultBindingFlags参数、参数、null参数BinderObject[]nullnull参数指定。CultureInfo

若要使用 SetValue 该方法,请先获取一个 Type 表示类的对象。 从中 Type获取 PropertyInfo 对象。 从对象中 PropertyInfo 调用 SetValue 该方法。

注释

如果使用标志授予ReflectionPermissionReflectionPermissionFlag.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

对象与目标类型不匹配,或者属性是实例属性,但 objnull

中的 index 参数数与索引属性采用的参数数不匹配。

尝试在类中非法访问私有或受保护的方法。

设置属性值时出错。 例如,为索引属性指定的索引值已超过范围。 该 InnerException 属性指示错误的原因。

示例

以下示例定义一个名为读写属性的TestClassCaption类。 它显示属性的 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

以下示例使用三个属性声明名为 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(零)个元素,则不会为该属性编制索引。

这是一种方便的方法,它调用抽象SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)方法的运行时实现,BindingFlags.Default指定BindingFlags参数、null参数Bindernull参数。CultureInfo

若要使用 SetValue 该方法,请先获取一个 Type 表示类的对象。 从中 Type获取 PropertyInfo。 从中PropertyInfoSetValue,使用该方法。

注释

在 .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

以下枚举成员的按位组合,用于指定调用属性: InvokeMethod、、 CreateInstanceStaticGetFieldSetFieldGetPropertySetProperty。 必须指定合适的调用属性。 例如,若要调用静态成员,请设置 Static 标志。

binder
Binder

一个对象,它允许绑定、强制参数类型、调用成员,以及通过反射检索 MemberInfo 对象。 binder如果是null,则使用默认绑定器。

index
Object[]

索引属性的可选索引值。 此值应 null 适用于非索引属性。

culture
CultureInfo

要为其本地化资源的区域性。 如果未为此区域性本地化资源, Parent 则会在搜索匹配项时连续调用该属性。 如果此值是 null,则从 CurrentUICulture 属性获取特定于区域性的信息。

实现

例外

index 数组不包含所需的参数类型。

-或-

找不到该属性的访问 set 器。

-或-

value 无法转换为类型 PropertyType

对象与目标类型不匹配,或者属性是实例属性,但 objnull

中的 index 参数数与索引属性采用的参数数不匹配。

尝试在类中非法访问私有或受保护的方法。

设置属性值时出错。 例如,为索引属性指定的索引值已超过范围。 该 InnerException 属性指示错误的原因。

注解

如果此PropertyInfo对象是值类型,valuenull则属性将设置为该类型的默认值。

若要确定属性是否已编制索引,请使用 GetIndexParameters 该方法。 如果生成的数组具有 0(零)个元素,则不会为该属性编制索引。

对于完全受信任的代码,将忽略访问限制。 也就是说,每当完全信任代码时,都可以通过反射访问和调用专用构造函数、方法、字段和属性。

若要使用该方法 SetValue ,请先获取类 Type。 从中 Type获取 PropertyInfo。 从中PropertyInfoSetValue,使用该方法。

注释

如果使用标志授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess调用方,并且非公共成员的授予集仅限于调用方授予集或子集,则此方法可用于访问非公共成员。 (请参阅反射的安全注意事项。)若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。

适用于