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);
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.
Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、Exception を代わりにキャッチします。In the .NET for Windows Store apps or the Portable Class Library, catch Exception instead.
obj
の型がターゲット型と一致しないか、またはプロパティがインスタンス プロパティですが、obj
は null
です。The type of obj
does not match the target type, or a property is an instance property but obj
is null
.
Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、基本クラスの例外である MemberAccessException を代わりにキャッチします。In the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.
プロパティ値の設定中にエラーが発生しました。An error occurred while setting the property value. InnerException プロパティは、エラーの理由を示します。The InnerException property indicates the reason for the error.
例
次の例では、1 Example
つstatic
の (Shared
Visual Basic) と1つのインスタンスプロパティを持つという名前のクラスを宣言します。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 null
Binder
BindingFlags
パラメーター null
Object[]
にはを指定し、にはを指定します。null
の場合CultureInfo
。This 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. オブジェクトから、 SetValueメソッドを呼び出します。 PropertyInfoFrom the PropertyInfo object, call the SetValue method.
注意
以降では、このメソッドを使用して、呼び出し元がReflectionPermissionFlag.RestrictedMemberAccessフラグで許可ReflectionPermissionされていて、非パブリックメンバーの許可セットが呼び出し元の許可セットまたはサブセットに制限されている場合に、非パブリックメンバーにアクセスできます。 .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1著作.Starting with the .NET Framework 2.0 Service Pack 1.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.NET Framework 3.5 以降を対象とする必要があります。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.
セキュリティ
ReflectionPermission
などの機構をInvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])使用して遅延バインディングが呼び出された場合。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). MemberAccess (関連する列挙体)Associated enumeration: MemberAccess.
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);
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. インデックス付きでないプロパティの場合は、この値を null
にする必要があります。This 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.
Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、Exception を代わりにキャッチします。In the .NET for Windows Store apps or the Portable Class Library, catch Exception instead.
obj
は null
です。The 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.
Windows ストア アプリ用 .NET またはポータブル クラス ライブラリでは、基本クラスの例外である MemberAccessException を代わりにキャッチします。In the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, MemberAccessException, instead.
プロパティ値の設定中にエラーが発生しました。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
いう名前Caption
の読み取り/書き込みプロパティを持つという名前のクラスを定義します。The 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
ではないため、引数はnull
になります。Note that, because the Caption
property is not a parameter array, the index
argument is null
.
次の例では、 Example
static
プロパティ (Shared
Visual Basic)、インスタンスプロパティ、およびインデックス付きインスタンスプロパティという3つのプロパティを使用して、という名前のクラスを宣言します。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 theDefault
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 isItem
, 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. この例では、名前はIndexedInstanceProperty
です。In this example, the name isIndexedInstanceProperty
.でC++は、
default
指定子を使用して、インデックス付きプロパティを既定のインデックス付きプロパティ (クラスインデクサー) にすることができます。In C++, thedefault
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 isItem
, 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オブジェクトが値value
型であり、がnull
の場合、プロパティはその型の既定値に設定されます。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
CultureInfo
あり、 BindingFlags.Defaultパラメーター null
Binder
には、には、 null
、にはを指定します。This 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. から、 PropertyInfoを取得します。 TypeFrom the Type, get the PropertyInfo. から、 SetValueメソッドを使用します。 PropertyInfoFrom the PropertyInfo, use the SetValue method.
注意
以降では、このメソッドを使用して、呼び出し元がReflectionPermissionFlag.RestrictedMemberAccessフラグで許可ReflectionPermissionされていて、非パブリックメンバーの許可セットが呼び出し元の許可セットまたはサブセットに制限されている場合に、非パブリックメンバーにアクセスできます。 .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1著作.Starting with the .NET Framework 2.0 Service Pack 1.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.NET Framework 3.5 以降を対象とする必要があります。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.
セキュリティ
ReflectionPermission
などの機構をInvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])使用して遅延バインディングが呼び出された場合。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). MemberAccess (関連する列挙体)Associated enumeration: MemberAccess.
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);
abstract member SetValue : obj * obj * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> unit
パラメーター
- obj
- Object
プロパティ値が設定されるオブジェクト。The object whose property value will be set.
- value
- Object
新しいプロパティ値。The new property value.
- invokeAttr
- BindingFlags
呼び出し属性を指定する次の列挙型メンバーのビットごとの組み合わせ: InvokeMethod
、CreateInstance
、Static
、GetField
、SetField
、GetProperty
または SetProperty
。A 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. binder
が null
の場合は、既定のバインダーが使用されます。If binder
is null
, the default binder is used.
- index
- Object[]
インデックス付きプロパティのインデックス値 (省略可能)。Optional index values for indexed properties. インデックス付きでないプロパティの場合は、この値を null
にする必要があります。This 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.
オブジェクトがターゲット型と一致しないか、またはプロパティがインスタンス プロパティですが、obj
は null
です。The 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オブジェクトが値value
型であり、がnull
の場合、プロパティはその型の既定値に設定されます。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
メソッドを使用するには、まずクラスType
を取得します。To use the SetValue
method, first get the class Type
. から、 PropertyInfo
を取得します。 Type
From the Type
, get the PropertyInfo
. から、 SetValue
メソッドを使用します。 PropertyInfo
From the PropertyInfo
, use the SetValue
method.
注意
以降では、このメソッドを使用して、呼び出し元がReflectionPermissionFlag.RestrictedMemberAccessフラグで許可ReflectionPermissionされていて、非パブリックメンバーの許可セットが呼び出し元の許可セットまたはサブセットに制限されている場合に、非パブリックメンバーにアクセスできます。 .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1著作.Starting with the .NET Framework 2.0 Service Pack 1.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.NET Framework 3.5 以降を対象とする必要があります。To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.
セキュリティ
ReflectionPermission
などの機構をInvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])使用して遅延バインディングが呼び出された場合。when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). MemberAccess (関連する列挙体)Associated enumeration: MemberAccess.