PropertyInfo.SetValue Metódus
Definíció
Fontos
Egyes információk olyan, kiadás előtti termékekre vonatkoznak, amelyek a kiadásig még jelentősen módosulhatnak. A Microsoft nem vállal kifejezett vagy törvényi garanciát az itt megjelenő információért.
Beállítja egy adott objektum tulajdonságértékét.
Túlterhelések
| Name | Description |
|---|---|
| SetValue(Object, Object) |
Egy megadott objektum tulajdonságértékének beállítása. |
| SetValue(Object, Object, Object[]) |
Beállítja egy adott objektum tulajdonságértékét az indextulajdonságok opcionális indexértékeivel. |
| SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) |
Ha egy származtatott osztályban felülbírált, beállítja egy adott objektum tulajdonságértékét, amely rendelkezik a megadott kötéssel, indextel és kultúrával kapcsolatos információkkal. |
SetValue(Object, Object)
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
Egy megadott objektum tulajdonságértékének beállítása.
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)
Paraméterek
- obj
- Object
Az az objektum, amelynek a tulajdonságértéke be lesz állítva.
- value
- Object
Az új tulajdonság értéke.
Kivételek
A tulajdonság tartozéka set nem található.
-vagy-
value nem konvertálható a következő típusra PropertyType: .
A típus obj nem egyezik a céltípussal, vagy egy tulajdonság egy példánytulajdonság, de obj az null.
Megjegyzés: Az .NET Windows Áruházbeli alkalmazások vagy a Portable Osztálytár esetében inkább Exception.
Illegális kísérlet történt egy privát vagy védett metódus elérésére egy osztályon belül.
Megjegyzés: Az .NET Windows Áruházbeli alkalmazások vagy a Portable Class Library esetében inkább az alaposztály kivételét MemberAccessException.
Hiba történt a tulajdonságérték beállítása során. A InnerException tulajdonság a hiba okát jelzi.
Példák
Az alábbi példa egy Example nevű osztályt deklarál egy static (Shared Visual Basic) és egy példánytulajdonságtal. A példa a SetValue(Object, Object) metódussal módosítja az eredeti tulajdonságértékeket, és megjeleníti az eredeti és a végső értékeket.
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
Megjegyzések
A SetValue(Object, Object) túlterhelés egy nem indexelt tulajdonság értékét állítja be. Annak megállapításához, hogy egy tulajdonság indexelt-e, hívja meg a metódust GetIndexParameters . Ha az eredményként kapott tömb 0 (nulla) elemet tartalmaz, a tulajdonság nincs indexelve. Indexelt tulajdonság értékének beállításához hívja meg a túlterhelést SetValue(Object, Object, Object[]) .
Ha az objektum tulajdonságtípusa PropertyInfo értéktípus, és value az null, akkor a tulajdonság az adott típus alapértelmezett értékére lesz beállítva.
Ez egy kényelmi módszer, amely meghívja az absztrakt SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) metódus futtatókörnyezeti implementációját, megadva BindingFlags.Default a paramétert, BindingFlags a nullBinder , null a Object[]és null a CultureInfo.
A SetValue metódus használatához először szerezze be Type az osztályt jelképező objektumot. TypeA helyről szerezze be az PropertyInfo objektumot. PropertyInfo Az objektumból hívja meg a metódustSetValue.
Note
Ez a módszer akkor használható a nem nyilvános tagok elérésére, ha a hívó a jelölővel ReflectionPermission rendelkezikReflectionPermissionFlag.RestrictedMemberAccess, és ha a nem nyilvános tagok támogatási készlete a hívó támogatási csoportjára vagy annak egy részhalmazára korlátozódik. (Lásd: A tükröződés biztonsági szempontjai.) A funkció használatához az alkalmazásnak .NET Framework 3.5-ös vagy újabb verziójára kell irányulnia.
A következőre érvényes:
SetValue(Object, Object, Object[])
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
Beállítja egy adott objektum tulajdonságértékét az indextulajdonságok opcionális indexértékeivel.
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())
Paraméterek
- obj
- Object
Az az objektum, amelynek a tulajdonságértéke be lesz állítva.
- value
- Object
Az új tulajdonság értéke.
- index
- Object[]
Nem kötelező indexértékek indexelt tulajdonságokhoz. Ennek az értéknek nem indexelt tulajdonságoknak kell lennie null .
Megvalósítás
Kivételek
A index tömb nem tartalmazza a szükséges argumentumtípust.
-vagy-
A tulajdonság tartozéka set nem található.
-vagy-
value nem konvertálható a következő típusra PropertyType: .
Az objektum nem egyezik a céltípussal, vagy egy tulajdonság egy példánytulajdonság, de obj az null.
Megjegyzés: Az .NET Windows Áruházbeli alkalmazások vagy a Portable Osztálytár esetében inkább Exception.
A paraméterek index száma nem egyezik meg az indexelt tulajdonság által használt paraméterek számával.
Illegális kísérlet történt egy privát vagy védett metódus elérésére egy osztályon belül.
Megjegyzés: Az .NET Windows Áruházbeli alkalmazások vagy a Portable Class Library esetében inkább az alaposztály kivételét MemberAccessException.
Hiba történt a tulajdonságérték beállítása során. Egy indexelt tulajdonsághoz megadott indexérték például túllépi a tartományt. A InnerException tulajdonság a hiba okát jelzi.
Példák
Az alábbi példa egy olyan osztályt határoz meg, amelynek írási-olvasási TestClass tulajdonsága el van nevezve Caption. Megjeleníti a tulajdonság alapértelmezett értékét Caption , meghívja a SetValue metódust a tulajdonság értékének módosítására, és megjeleníti az eredményt.
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.
Vegye figyelembe, hogy mivel a Caption tulajdonság nem paramétertömb, az argumentum az indexnull.
Az alábbi példa egy Example nevű osztályt deklarál három tulajdonságokkal: egy static tulajdonsággal (Shared a Visual Basic), egy példánytulajdonságsal és egy indexelt példánytulajdonságsal. A példa a SetValue metódussal módosítja a tulajdonságok alapértelmezett értékeit, és megjeleníti az eredeti és a végső értékeket.
Az indexelt példánytulajdonságok tükröződéssel való kereséséhez használt név a nyelvtől és a tulajdonságra alkalmazott attribútumoktól függően eltérő.
A Visual Basic a tulajdonság neve mindig a tulajdonság tükröződésekkel való keresésére szolgál. A kulcsszóval
Defaultalapértelmezett indexelt tulajdonságként állíthatja be a tulajdonságot, ebben az esetben kihagyhatja a nevet a tulajdonság elérésekor, ahogyan ebben a példában is látható. A tulajdonság nevét is használhatja.A C#-ban az indexelt példány tulajdonsága egy indexelőnek nevezett alapértelmezett tulajdonság, és a rendszer soha nem használja a nevet a kódban lévő tulajdonság elérésekor. Alapértelmezés szerint a tulajdonság
Itemneve az , és ezt a nevet kell használnia, amikor tükröződéssel keresi a tulajdonságot. Az attribútummal IndexerNameAttribute más nevet adhat az indexelőnek. Ebben a példában a névIndexedInstanceProperty.
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'
Megjegyzések
Ha ez az PropertyInfo objektum értéktípus, és value az null, akkor a tulajdonság az adott típus alapértelmezett értékére lesz beállítva.
Annak megállapításához, hogy egy tulajdonság indexelt-e, használja a metódust GetIndexParameters . Ha az eredményként kapott tömb 0 (nulla) elemet tartalmaz, a tulajdonság nincs indexelve.
Ez egy kényelmi módszer, amely meghívja az absztrakt SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) metódus futtatókörnyezeti implementációját, megadva BindingFlags.Default a BindingFlags paramétert, null a Binderés null a .CultureInfo
A SetValue metódus használatához először szerezze be Type az osztályt jelképező objektumot. TypeA helyről szerezze be a PropertyInfo. Használja a PropertyInfometódust.SetValue
Note
A .NET Keretrendszerben ez a módszer használható a nem nyilvános tagok elérésére, ha a hívó ReflectionPermission kapott a ReflectionPermissionFlag.RestrictedMemberAccess jelzővel, és ha a nem nyilvános tagok támogatási halmaza a hívó támogatási készletére vagy annak egy részhalmazára korlátozódik. (Lásd: A tükröződés biztonsági szempontjai.) A funkció használatához az alkalmazásnak .NET Framework 3.5-ös vagy újabb verziójára kell irányulnia.
A következőre érvényes:
SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
- Forrás:
- PropertyInfo.cs
Ha egy származtatott osztályban felülbírált, beállítja egy adott objektum tulajdonságértékét, amely rendelkezik a megadott kötéssel, indextel és kultúrával kapcsolatos információkkal.
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)
Paraméterek
- obj
- Object
Az az objektum, amelynek a tulajdonságértéke be lesz állítva.
- value
- Object
Az új tulajdonság értéke.
- invokeAttr
- BindingFlags
A következő enumerálási tagok bitenkénti kombinációja, amelyek megadják a meghívási attribútumot: InvokeMethod, , CreateInstance, Static, GetFieldSetField, GetPropertyvagy SetProperty. Meg kell adnia egy megfelelő meghívási attribútumot. Statikus tag meghívásához például állítsa be a jelölőt Static .
- binder
- Binder
Olyan objektum, amely lehetővé teszi az argumentumtípusok kötését, kényszerítését, a tagok meghívását és az objektumok visszaverésen keresztüli lekérését MemberInfo . Ha binder igen null, akkor a rendszer az alapértelmezett kötőanyagot használja.
- index
- Object[]
Nem kötelező indexértékek indexelt tulajdonságokhoz. Ennek az értéknek nem indexelt tulajdonságoknak kell lennie null .
- culture
- CultureInfo
Az a kultúra, amelyhez az erőforrást honosítanák. Ha az erőforrás nincs honosítva ehhez a kultúrához, a rendszer egymás után hívja meg a Parent tulajdonságot egyezés keresésekor. Ha ez az érték, nulla kultúraspecifikus információk a CurrentUICulture tulajdonságból lesznek lekértek.
Megvalósítás
Kivételek
A index tömb nem tartalmazza a szükséges argumentumtípust.
-vagy-
A tulajdonság tartozéka set nem található.
-vagy-
value nem konvertálható a következő típusra PropertyType: .
Az objektum nem egyezik a céltípussal, vagy egy tulajdonság egy példánytulajdonság, de obj az null.
A paraméterek index száma nem egyezik meg az indexelt tulajdonság által használt paraméterek számával.
Illegális kísérlet történt egy privát vagy védett metódus elérésére egy osztályon belül.
Hiba történt a tulajdonságérték beállítása során. Egy indexelt tulajdonsághoz megadott indexérték például túllépi a tartományt. A InnerException tulajdonság a hiba okát jelzi.
Megjegyzések
Ha ez az PropertyInfo objektum értéktípus, és value az null, akkor a tulajdonság az adott típus alapértelmezett értékére lesz beállítva.
Annak megállapításához, hogy egy tulajdonság indexelt-e, használja a metódust GetIndexParameters . Ha az eredményként kapott tömb 0 (nulla) elemet tartalmaz, a tulajdonság nincs indexelve.
A hozzáférési korlátozások figyelmen kívül lesznek hagyva a teljes mértékben megbízható kód esetében. A magánkonstruktorok, metódusok, mezők és tulajdonságok a Reflection használatával érhetők el és hívhatók meg, amikor a kód teljes mértékben megbízható.
A metódus használatához SetValue először szerezze be az osztályt Type.
TypeA helyről szerezze be a PropertyInfo. Használja a PropertyInfometódust.SetValue
Note
Ez a módszer akkor használható a nem nyilvános tagok elérésére, ha a hívó a jelölővel ReflectionPermission rendelkezikReflectionPermissionFlag.RestrictedMemberAccess, és ha a nem nyilvános tagok támogatási készlete a hívó támogatási csoportjára vagy annak egy részhalmazára korlátozódik. (Lásd: A tükröződés biztonsági szempontjai.) A funkció használatához az alkalmazásnak .NET Framework 3.5-ös vagy újabb verziójára kell irányulnia.