本文由机器翻译。若要查看英语原文,请勾选“英语”复选框。 也可将鼠标指针移到文本上,在弹出窗口中显示英语原文。
翻译
英语

PropertyInfo.SetValue 方法 (Object, Object, Object[])

 

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

命名空间:   System.Reflection
程序集:  mscorlib(位于 mscorlib.dll)

public virtual void SetValue(
	object obj,
	object value,
	object[] index
)

参数

obj
Type: System.Object

将设置其属性值的对象。

value
Type: System.Object

新的属性值。

index
Type: System.Object[]

索引化属性的可选索引值。 对于非索引化属性,该值应为 null

Exception Condition
ArgumentException

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

- 或 -

找不到该属性的 set 取值函数。

- 或 -

value 无法转换为 PropertyType 的类型。

TargetException

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

TargetParameterCountException

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

MethodAccessException

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

TargetInvocationException

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

If this T:System.Reflection.PropertyInfo object is a value type and value is null, then the property will be set to the default value for that type.

To determine whether a property is indexed, use the M:System.Reflection.PropertyInfo.GetIndexParameters method. If the resulting array has 0 (zero) elements, the property is not indexed.

This is a convenience method that calls the runtime implementation of the abstract M:System.Reflection.PropertyInfo.SetValue(System.Object,System.Object,System.Reflection.BindingFlags,System.Reflection.Binder,System.Object[],System.Globalization.CultureInfo) method, specifying F:System.Reflection.BindingFlags.Default for the BindingFlags parameter, null for Binder, and null for CultureInfo.

To use the Overload:System.Reflection.PropertyInfo.SetValue method, first get a T:System.Type object that represents the class. From the T:System.Type, get the T:System.Reflection.PropertyInfo. From the T:System.Reflection.PropertyInfo, use the Overload:System.Reflection.PropertyInfo.SetValue method.

System_CAPS_note说明

Starting with the net_v20sp1_long, this method can be used to access non-public members if the caller has been granted T:System.Security.Permissions.ReflectionPermission with the F:System.Security.Permissions.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.)

To use this functionality, your application should target the net_v35_long or later.

The following example defines a class named TestClass that has a read-write property named Caption. It displays the default value of the Caption property, calls the M:System.Reflection.PropertyInfo.SetValue(System.Object,System.Object,System.Object[]) method to change the property value, and displays the result.

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.
*/

Note that, because the Caption property is not a parameter array, the index argument is null.

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. The example uses the M:System.Reflection.PropertyInfo.SetValue(System.Object,System.Object,System.Object[]) 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.

  • In Visual Basic, the property name is always used to search for the property with reflection. 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.

  • 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. By default, the name of the property is Item, and you must use that name when you search for the property with reflection. You can use the T:System.Runtime.CompilerServices.IndexerNameAttribute attribute to give the indexer a different name. In this example, the name is IndexedInstanceProperty.

  • In C++, the default specifier can be used to make an indexed property a default indexed property (class indexer). 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. You can use the T:System.Runtime.CompilerServices.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 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 ApplicationException("IndexedInstanceProperty value can be the empty string, but it cannot be Nothing.");
            }
            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'
 */

ReflectionPermission

for accessing non-public members when the grant set of the non-public members is restricted to the caller's grant set, or a subset thereof. Associated enumeration: F:System.Security.Permissions.ReflectionPermissionFlag.RestrictedMemberAccess

ReflectionPermission

for accessing non-public members regardless of their grant set. Associated enumeration: F:System.Security.Permissions.ReflectionPermissionFlag.MemberAccess

ReflectionPermission

when invoked late-bound through mechanisms such as M:System.Type.InvokeMember(System.String,System.Reflection.BindingFlags,System.Reflection.Binder,System.Object,System.Object[],System.Reflection.ParameterModifier[],System.Globalization.CultureInfo,System.String[]). Associated enumeration: F:System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.

通用 Windows 平台
自 8 起可用
.NET Framework
自 1.1 起可用
可移植类库
可移植 .NET 平台 中受支持
Silverlight
自 2.0 起可用
Windows Phone Silverlight
自 7.0 起可用
Windows Phone
自 8.1 起可用
返回页首
显示: