PropertyInfo.SetValue 方法

定义

设置指定对象的属性值。Sets the property value for a specified object.

重载

SetValue(Object, Object)

设置指定对象的属性值。Sets the property value of a specified object.

SetValue(Object, Object, Object[])

用索引化属性的可选索引值设置指定对象的该属性值。Sets the property value of a specified object with optional index values for index properties.

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

当在派生类中重写时,为具有指定绑定、索引和区域性特定信息的指定对象设置属性值。When overridden in a derived class, sets the property value for a specified object that has the specified binding, index, and culture-specific information.

SetValue(Object, Object)

设置指定对象的属性值。Sets the property value of a specified 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

将设置其属性值的对象。The object whose property value will be set.

value
Object

新的属性值。The new property value.

例外

找不到该属性的 set 取值函数。The property's set accessor is not found.

-or- value 无法转换为 PropertyType 的类型。value cannot be converted to the type of PropertyType.

obj 的类型与目标类型不匹配,或属性是实例属性,但 objnullThe type of obj does not match the target type, or a property is an instance property but obj is null.

试图非法访问类中的私有或受保护方法。There was an illegal attempt to access a private or protected method inside a class.

设置属性值时出错。An error occurred while setting the property value. InnerException 属性指示出错的原因。The InnerException property indicates the reason for the error.

示例

下面的示例声明一个名为的类,其中 Example 一个 static (Shared Visual Basic) 和一个实例属性中。The following example declares a class named Example with one static (Shared in Visual Basic) and one instance property. 该示例使用 SetValue(Object, Object) 方法来更改原始属性值并显示原始值和最终值。The example uses the SetValue(Object, Object) method to change the original property values and displays the original and final values.

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)重载设置非索引属性的值。The SetValue(Object, Object) overload sets the value of a non-indexed property. 若要确定是否已对某个属性编制索引,请调用 GetIndexParameters 方法。To determine whether a property is indexed, call the GetIndexParameters method. 如果生成的数组有0个 (零) 元素,则不会为该属性编制索引。If the resulting array has 0 (zero) elements, the property is not indexed. 若要设置索引属性的值,请调用 SetValue(Object, Object, Object[]) 重载。To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload.

如果此对象的属性类型 PropertyInfo 为值类型并且 value 为,则 null 属性将设置为该类型的默认值。If the property type of this PropertyInfo object is a value type and value is null, the property will be set to the default value for that type.

这是一种便捷的方法,它调用抽象方法的运行时实现 SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) ,并为参数指定,为、 BindingFlags.Default 和指定 BindingFlags null Binder null Object[] null CultureInfoThis is a convenience method that calls the runtime implementation of the abstract SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) method, specifying BindingFlags.Default for the BindingFlags parameter, null for Binder, null for Object[], and null for CultureInfo.

若要使用 SetValue 方法,请首先获取 Type 表示类的对象。To use the SetValue method, first get a Type object that represents the class. 在中 Type ,获取 PropertyInfo 对象。From the Type, get the PropertyInfo object. PropertyInfo 对象调用 SetValue 方法。From the PropertyInfo object, call the SetValue method.

备注

从 .NET Framework 2.0 Service Pack 1 开始,此方法可用于访问非公共成员(如果调用方已 ReflectionPermission 使用 ReflectionPermissionFlag.RestrictedMemberAccess 标志授予),并且如果非公共成员的授予集限制为调用方的授予集或其子集,则可使用此方法访问非公共成员。Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (参阅 反射的安全注意事项) (See Security Considerations for Reflection.)

若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5 or later.

适用于

SetValue(Object, Object, Object[])

用索引化属性的可选索引值设置指定对象的该属性值。Sets the property value of a specified object with optional index values for index properties.

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

将设置其属性值的对象。The object whose property value will be set.

value
Object

新的属性值。The new property value.

index
Object[]

索引化属性的可选索引值。Optional index values for indexed properties. 对于非索引化属性,该值应为 nullThis value should be null for non-indexed properties.

实现

例外

index 数组不包含所需的参数类型。The index array does not contain the type of arguments needed.

-or- 找不到该属性的 set 取值函数。The property's set accessor is not found.

-or- value 无法转换为 PropertyType 的类型。value cannot be converted to the type of PropertyType.

该对象与目标类型不匹配,或者某属性是实例属性但 objnullThe object does not match the target type, or a property is an instance property but obj is null.

index 中的参数数量与索引属性采用的参数数量不匹配。The number of parameters in index does not match the number of parameters the indexed property takes.

试图非法访问类中的私有或受保护方法。There was an illegal attempt to access a private or protected method inside a class.

设置属性值时出错。An error occurred while setting the property value. 例如,为一个索引属性指定的索引值超出范围。For example, an index value specified for an indexed property is out of range. InnerException 属性指示出错的原因。The InnerException property indicates the reason for the error.

示例

下面的示例定义一个名为 TestClass 的类,该类具有名为的读写属性 CaptionThe following example defines a class named TestClass that has a read-write property named Caption. 它显示属性的默认值 Caption ,调用 SetValue 方法以更改属性值,并显示结果。It displays the default value of the Caption property, calls the SetValue method to change the property value, and displays the result.

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 参数是 nullNote that, because the Caption property is not a parameter array, the index argument is null.

下面的示例声明一个名为 Example 的类,该类具有三个属性: static Shared Visual Basic) 、实例属性和索引实例属性中 (属性。The following example declares a class named Example with three properties: a static property (Shared in Visual Basic), an instance property, and an indexed instance property. 该示例使用 SetValue 方法来更改属性的默认值,并显示原始值和最终值。The example uses the SetValue method to change the default values of the properties and displays the original and final values.

用于使用反射搜索索引实例属性的名称根据语言和应用于属性的特性而有所不同。The name that is used to search for an indexed instance property with reflection is different depending on the language and on attributes applied to the property.

  • 在 Visual Basic 中,始终使用属性名称通过反射搜索属性。In Visual Basic, the property name is always used to search for the property with reflection. 可以使用关键字将 Default 属性设为默认的索引属性,在这种情况下,可以在访问属性时省略名称,如本示例中所示。You can use the Default keyword to make the property a default indexed property, in which case you can omit the name when accessing the property, as in this example. 你还可以使用属性名称。You can also use the property name.

  • 在 c # 中,索引实例属性是名为索引器的默认属性,在代码中访问属性时从不使用该名称。In C#, the indexed instance property is a default property called an indexer, and the name is never used when accessing the property in code. 默认情况下,属性的名称为 Item ,并且在使用反射搜索属性时必须使用该名称。By default, the name of the property is Item, and you must use that name when you search for the property with reflection. 您可以使用 IndexerNameAttribute 属性为索引器指定一个不同的名称。You can use the IndexerNameAttribute attribute to give the indexer a different name. 在本示例中,该名称为 IndexedInstancePropertyIn this example, the name is IndexedInstanceProperty.

  • 在 c + + 中, default 说明符可用于使索引属性成为 (类索引器) 的默认索引属性。In C++, the default specifier can be used to make an indexed property a default indexed property (class indexer). 在这种情况下,属性的名称默认为,在使用 Item 反射搜索属性时必须使用该名称,如本示例中所示。In that case, the name of the property by default is Item, and you must use that name when you search for the property with reflection, as in this example. 您可以使用 IndexerNameAttribute 属性在反射中为类索引器指定一个不同的名称,但不能使用该名称在代码中访问该属性。You can use the IndexerNameAttribute attribute to give the class indexer a different name in reflection, but you cannot use that name to access the property in code. 不是类索引器的索引属性是在代码和反射中使用其名称访问的。An indexed property that is not a class indexer is accessed using its name, both in code and in reflection.

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 ,则属性将设置为该类型的默认值。If this PropertyInfo object is a value type and value is null, then the property will be set to the default value for that type.

若要确定是否已对某个属性编制索引,请使用 GetIndexParameters 方法。To determine whether a property is indexed, use the GetIndexParameters method. 如果生成的数组有0个 (零) 元素,则不会为该属性编制索引。If the resulting array has 0 (zero) elements, the property is not indexed.

这是一种便捷的方法,它调用抽象方法的运行时实现 SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) ,并为参数指定,并为指定 BindingFlags.Default BindingFlags 参数 null Binder null CultureInfoThis is a convenience method that calls the runtime implementation of the abstract SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) method, specifying BindingFlags.Default for the BindingFlags parameter, null for Binder, and null for CultureInfo.

若要使用 SetValue 方法,请首先获取 Type 表示类的对象。To use the SetValue method, first get a Type object that represents the class. 从中 Type 获取 PropertyInfoFrom the Type, get the PropertyInfo. 从中 PropertyInfo ,使用 SetValue 方法。From the PropertyInfo, use the SetValue method.

备注

从 .NET Framework 2.0 Service Pack 1 开始,此方法可用于访问非公共成员(如果调用方已 ReflectionPermission 使用 ReflectionPermissionFlag.RestrictedMemberAccess 标志授予),并且如果非公共成员的授予集限制为调用方的授予集或其子集,则可使用此方法访问非公共成员。Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (参阅 反射的安全注意事项) (See Security Considerations for Reflection.)

若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5 or later.

适用于

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

当在派生类中重写时,为具有指定绑定、索引和区域性特定信息的指定对象设置属性值。When overridden in a derived class, sets the property value for a specified object that has the specified binding, index, and culture-specific information.

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

将设置其属性值的对象。The object whose property value will be set.

value
Object

新的属性值。The new property value.

invokeAttr
BindingFlags

以下指定该调用特性的枚举成员的按位组合:InvokeMethodCreateInstanceStaticGetFieldSetFieldGetPropertySetPropertyA bitwise combination of the following enumeration members that specify the invocation attribute: InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty, or SetProperty. 必须指定合适的调用属性。You must specify a suitable invocation attribute. 例如,为了调用静态成员,设置 Static 标志。For example, to invoke a static member, set the Static flag.

binder
Binder

一个对象,它启用绑定、对参数类型的强制、对成员的调用,以及通过反射对 MemberInfo 对象的检索。An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. 如果 bindernull,则使用默认联编程序。If binder is null, the default binder is used.

index
Object[]

索引化属性的可选索引值。Optional index values for indexed properties. 对于非索引化属性,该值应为 nullThis value should be null for non-indexed properties.

culture
CultureInfo

要为其本地化资源的区域性。The culture for which the resource is to be localized. 请注意,如果没有为此区域性本地化该资源,则在搜索匹配项的过程中将继续调用 Parent 属性。If the resource is not localized for this culture, the Parent property will be called successively in search of a match. 如果该值为 null,则从 CurrentUICulture 属性获取区域性的特定信息。If this value is null, the culture-specific information is obtained from the CurrentUICulture property.

实现

例外

index 数组不包含所需的参数类型。The index array does not contain the type of arguments needed.

-or- 找不到该属性的 set 取值函数。The property's set accessor is not found.

-or- value 无法转换为 PropertyType 的类型。value cannot be converted to the type of PropertyType.

该对象与目标类型不匹配,或者某属性是实例属性但 objnullThe object does not match the target type, or a property is an instance property but obj is null.

index 中的参数数量与索引属性采用的参数数量不匹配。The number of parameters in index does not match the number of parameters the indexed property takes.

试图非法访问类中的私有或受保护方法。There was an illegal attempt to access a private or protected method inside a class.

设置属性值时出错。An error occurred while setting the property value. 例如,为一个索引属性指定的索引值超出范围。For example, an index value specified for an indexed property is out of range. InnerException 属性指示出错的原因。The InnerException property indicates the reason for the error.

注解

如果此 PropertyInfo 对象是值类型并且 valuenull ,则属性将设置为该类型的默认值。If this PropertyInfo object is a value type and value is null, then the property will be set to the default value for that type.

若要确定是否已对某个属性编制索引,请使用 GetIndexParameters 方法。To determine whether a property is indexed, use the GetIndexParameters method. 如果生成的数组有0个 (零) 元素,则不会为该属性编制索引。If the resulting array has 0 (zero) elements, the property is not indexed.

对于完全受信任的代码,将忽略访问限制。Access restrictions are ignored for fully trusted code. 也就是说,只要代码完全受信任,就可以通过反射访问和调用私有构造函数、方法、字段和属性。That is, private constructors, methods, fields, and properties can be accessed and invoked via Reflection whenever the code is fully trusted.

若要使用 SetValue 方法,请首先获取类 TypeTo use the SetValue method, first get the class Type. 从中 Type 获取 PropertyInfoFrom the Type, get the PropertyInfo. 从中 PropertyInfo ,使用 SetValue 方法。From the PropertyInfo, use the SetValue method.

备注

从 .NET Framework 2.0 Service Pack 1 开始,此方法可用于访问非公共成员(如果调用方已 ReflectionPermission 使用 ReflectionPermissionFlag.RestrictedMemberAccess 标志授予),并且如果非公共成员的授予集限制为调用方的授予集或其子集,则可使用此方法访问非公共成员。Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access non-public members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. (参阅 反射的安全注意事项) (See Security Considerations for Reflection.)

若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。To use this functionality, your application should target the .NET Framework 3.5 or later.

适用于