PropertyInfo.SetValue 方法 (System.Reflection)
Source:PropertyInfo.cs
Source:PropertyInfo.cs
Source:PropertyInfo.cs
用索引化属性的可选索引值设置指定对象的该属性值。
public:
virtual void SetValue(System::Object ^ obj, System::Object ^ value, cli::array
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。
实现
SetValue(Object, Object, Object[])
例外
ArgumentException
index 数组不包含所需的参数类型。
或
找不到该属性的 set 取值函数。
或
value 无法转换为 PropertyType 的类型。
TargetException
该对象与目标类型不匹配,或者某属性是实例属性但 obj 为 null。
注意:在 适用于 Windows 应用商店应用的 .NET 或 可移植类库中,请改为 catch Exception 。
TargetParameterCountException
index 中的参数数量与索引属性采用的参数数量不匹配。
MethodAccessException
试图非法访问类中的私有或受保护方法。
注意:在 适用于 Windows 应用商店应用的 .NET 或 可移植类库中,改为捕获基类异常 MemberAccessException。
TargetInvocationException
设置属性值时出错。 例如,为一个索引属性指定的索引值超出范围。
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
public:
Example()
{
_instanceProperty = 42;
_indexedInstanceProperty = gcnew Dictionary
};
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
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
new Dictionary
// 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 对象是值类型且 value 为 null,则 属性将设置为该类型的默认值。
若要确定是否为属性编制索引,请使用 GetIndexParameters 方法。 如果生成的数组具有 0 个 (零个) 元素,则不会为属性编制索引。
这是一种方便的方法,它调用抽象SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)方法的运行时实现,为 BindingFlags 参数指定 BindingFlags.Default ,null为 指定 null ,为 Binder指定 。CultureInfo
若要使用 SetValue 方法,请首先获取表示 Type 类的 对象。
Type从 中获取 PropertyInfo。 在 中 PropertyInfo,使用 SetValue 方法。
注意
从 .NET Framework 2.0 开始,如果调用方已使用 标志授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess,并且非公共成员的授权集仅限于调用方授权集或其子集,则此方法可用于访问非公共成员。 (请参阅 Reflection.) 若要使用此功能,应用程序应面向 .NET Framework 3.5 或更高版本。
适用于
- 选手访谈
- 2026-02-28 19:10:52