Udostępnij za pośrednictwem


PropertyInfo.SetValue Metoda

Definicja

Ustawia wartość właściwości dla określonego obiektu.

Przeciążenia

Nazwa Opis
SetValue(Object, Object)

Ustawia wartość właściwości określonego obiektu.

SetValue(Object, Object, Object[])

Ustawia wartość właściwości określonego obiektu z opcjonalnymi wartościami indeksu dla właściwości indeksu.

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

Po zastąpieniu w klasie pochodnej ustawia wartość właściwości dla określonego obiektu, który ma określone powiązanie, indeks i informacje specyficzne dla kultury.

SetValue(Object, Object)

Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs

Ustawia wartość właściwości określonego obiektu.

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)

Parametry

obj
Object

Obiekt, którego wartość właściwości zostanie ustawiona.

value
Object

Nowa wartość właściwości.

Wyjątki

Nie można odnaleźć metody dostępu set właściwości.

-lub-

value nie można przekonwertować na typ PropertyType.

Typ obj nie jest zgodny z typem docelowym lub właściwość jest właściwością wystąpienia, ale obj jest null.

W klasie nastąpiła nielegalna próba uzyskania dostępu do prywatnej lub chronionej metody.

Wystąpił błąd podczas ustawiania wartości właściwości. Właściwość InnerException wskazuje przyczynę błędu.

Przykłady

Poniższy przykład deklaruje klasę o nazwie Example z jedną właściwością static (Shared w Visual Basic) i jedną właściwość wystąpienia. W przykładzie użyto metody SetValue(Object, Object), aby zmienić oryginalne wartości właściwości i wyświetlić oryginalne i końcowe wartości.

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

Uwagi

Przeciążenie SetValue(Object, Object) ustawia wartość właściwości nieindeksowanej. Aby określić, czy właściwość jest indeksowana, wywołaj metodę GetIndexParameters. Jeśli wynikowa tablica ma 0 (zero), właściwość nie jest indeksowana. Aby ustawić wartość właściwości indeksowanej, wywołaj przeciążenie SetValue(Object, Object, Object[]).

Jeśli typ właściwości tego obiektu PropertyInfo jest typem wartości, a value jest null, właściwość zostanie ustawiona na wartość domyślną tego typu.

Jest to metoda wygody, która wywołuje implementację środowiska uruchomieniowego metody abstrakcyjnej SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo), określając BindingFlags.Default parametru BindingFlags, null dla Binder, null dla Object[]i null dla CultureInfo.

Aby użyć metody SetValue, najpierw pobierz obiekt Type reprezentujący klasę. Z Typepobierz obiekt PropertyInfo. Z obiektu PropertyInfo wywołaj metodę SetValue.

Nuta

Ta metoda może służyć do uzyskiwania dostępu do elementów członkowskich innych niż publiczne, jeśli obiekt wywołujący otrzymał ReflectionPermission flagę ReflectionPermissionFlag.RestrictedMemberAccess , a zestaw dotacji niepubliki członków jest ograniczony do zestawu dotacji obiektu wywołującego lub jego podzbioru. (Zobacz Zabezpieczenia dotyczące odbicia). Aby korzystać z tej funkcji, aplikacja powinna być docelowa .NET Framework 3.5 lub nowsza.

Dotyczy

SetValue(Object, Object, Object[])

Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs

Ustawia wartość właściwości określonego obiektu z opcjonalnymi wartościami indeksu dla właściwości indeksu.

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())

Parametry

obj
Object

Obiekt, którego wartość właściwości zostanie ustawiona.

value
Object

Nowa wartość właściwości.

index
Object[]

Opcjonalne wartości indeksu dla właściwości indeksowanych. Ta wartość powinna być null dla właściwości nieindeksowanych.

Implementuje

Wyjątki

Tablica index nie zawiera wymaganego typu argumentów.

-lub-

Nie można odnaleźć metody dostępu set właściwości.

-lub-

value nie można przekonwertować na typ PropertyType.

Obiekt nie jest zgodny z typem docelowym lub właściwość jest właściwością wystąpienia, ale obj jest null.

Liczba parametrów w index nie jest zgodna z liczbą parametrów pobieranych przez indeksowaną właściwość.

W klasie nastąpiła nielegalna próba uzyskania dostępu do prywatnej lub chronionej metody.

Wystąpił błąd podczas ustawiania wartości właściwości. Na przykład wartość indeksu określona dla właściwości indeksowanej jest poza zakresem. Właściwość InnerException wskazuje przyczynę błędu.

Przykłady

W poniższym przykładzie zdefiniowano klasę o nazwie TestClass, która ma właściwość read-write o nazwie Caption. Wyświetla on wartość domyślną właściwości Caption, wywołuje metodę SetValue, aby zmienić wartość właściwości i wyświetli wynik.

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.

Należy pamiętać, że ponieważ właściwość Caption nie jest tablicą parametrów, argument index jest null.

Poniższy przykład deklaruje klasę o nazwie Example z trzema właściwościami: właściwością static (Shared w Visual Basic), właściwością wystąpienia i właściwością indeksowanego wystąpienia. W przykładzie użyto metody SetValue, aby zmienić wartości domyślne właściwości i wyświetlić oryginalne i końcowe wartości.

Nazwa używana do wyszukiwania właściwości wystąpienia indeksowanego z odbiciem różni się w zależności od języka i atrybutów zastosowanych do właściwości.

  • W Visual Basic nazwa właściwości jest zawsze używana do wyszukiwania właściwości z odbiciem. Możesz użyć słowa kluczowego Default, aby właściwość została właściwością domyślną indeksowaną, w takim przypadku można pominąć nazwę podczas uzyskiwania dostępu do właściwości, jak w tym przykładzie. Możesz również użyć nazwy właściwości.

  • W języku C# właściwość indeksowanego wystąpienia jest właściwością domyślną o nazwie indeksator, a nazwa nigdy nie jest używana podczas uzyskiwania dostępu do właściwości w kodzie. Domyślnie nazwa właściwości to Itemi należy jej użyć podczas wyszukiwania właściwości z odbiciem. Możesz użyć atrybutu IndexerNameAttribute, aby nadać indeksatorowi inną nazwę. W tym przykładzie nazwa to IndexedInstanceProperty.

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'

Uwagi

Jeśli ten obiekt PropertyInfo jest typem wartości, a value jest null, właściwość zostanie ustawiona na wartość domyślną tego typu.

Aby określić, czy właściwość jest indeksowana, użyj metody GetIndexParameters. Jeśli wynikowa tablica ma 0 (zero), właściwość nie jest indeksowana.

Jest to metoda wygody, która wywołuje implementację środowiska uruchomieniowego metody abstrakcyjnej SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo), określając BindingFlags.Default parametru BindingFlags, null dla Binderi null dla CultureInfo.

Aby użyć metody SetValue, najpierw pobierz obiekt Type reprezentujący klasę. Z Typepobierz PropertyInfo. W PropertyInfoużyj metody SetValue.

Nuta

W programie .NET Framework ta metoda może służyć do uzyskiwania dostępu do elementów członkowskich innych niż publiczne, jeśli obiekt wywołujący otrzymał ReflectionPermission z flagą ReflectionPermissionFlag.RestrictedMemberAccess i jeśli zestaw dotacji niepubliki członków jest ograniczony do zestawu dotacji obiektu wywołującego lub jego podzbioru. (Zobacz Zabezpieczenia dotyczące odbicia). Aby korzystać z tej funkcji, aplikacja powinna być docelowa .NET Framework 3.5 lub nowsza.

Dotyczy

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

Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs
Źródło:
PropertyInfo.cs

Po zastąpieniu w klasie pochodnej ustawia wartość właściwości dla określonego obiektu, który ma określone powiązanie, indeks i informacje specyficzne dla kultury.

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)

Parametry

obj
Object

Obiekt, którego wartość właściwości zostanie ustawiona.

value
Object

Nowa wartość właściwości.

invokeAttr
BindingFlags

Bitowa kombinacja następujących elementów członkowskich wyliczenia, które określają atrybut wywołania: InvokeMethod, CreateInstance, Static, GetField, SetField, GetPropertylub SetProperty. Należy określić odpowiedni atrybut wywołania. Aby na przykład wywołać statyczny element członkowski, ustaw flagę Static.

binder
Binder

Obiekt, który umożliwia powiązanie, przymus typów argumentów, wywołanie elementów członkowskich i pobieranie obiektów MemberInfo przez odbicie. Jeśli binder jest null, zostanie użyty domyślny binder.

index
Object[]

Opcjonalne wartości indeksu dla właściwości indeksowanych. Ta wartość powinna być null dla właściwości nieindeksowanych.

culture
CultureInfo

Kultura, dla której zasób ma być zlokalizowany. Jeśli zasób nie jest zlokalizowany dla tej kultury, właściwość Parent będzie wywoływana kolejno w wyszukiwaniu dopasowania. Jeśli ta wartość jest null, informacje specyficzne dla kultury są uzyskiwane z właściwości CurrentUICulture.

Implementuje

Wyjątki

Tablica index nie zawiera wymaganego typu argumentów.

-lub-

Nie można odnaleźć metody dostępu set właściwości.

-lub-

value nie można przekonwertować na typ PropertyType.

Obiekt nie jest zgodny z typem docelowym lub właściwość jest właściwością wystąpienia, ale obj jest null.

Liczba parametrów w index nie jest zgodna z liczbą parametrów pobieranych przez indeksowaną właściwość.

W klasie nastąpiła nielegalna próba uzyskania dostępu do prywatnej lub chronionej metody.

Wystąpił błąd podczas ustawiania wartości właściwości. Na przykład wartość indeksu określona dla właściwości indeksowanej jest poza zakresem. Właściwość InnerException wskazuje przyczynę błędu.

Uwagi

Jeśli ten obiekt PropertyInfo jest typem wartości, a value jest null, właściwość zostanie ustawiona na wartość domyślną tego typu.

Aby określić, czy właściwość jest indeksowana, użyj metody GetIndexParameters. Jeśli wynikowa tablica ma 0 (zero), właściwość nie jest indeksowana.

Ograniczenia dostępu są ignorowane dla w pełni zaufanego kodu. Oznacza to, że dostęp do prywatnych konstruktorów, metod, pól i właściwości można uzyskać i wywołać za pomocą odbicia zawsze, gdy kod jest w pełni zaufany.

Aby użyć metody SetValue, najpierw pobierz klasę Type. Z Typepobierz PropertyInfo. W PropertyInfoużyj metody SetValue.

Nuta

Ta metoda może służyć do uzyskiwania dostępu do elementów członkowskich innych niż publiczne, jeśli obiekt wywołujący otrzymał ReflectionPermission flagę ReflectionPermissionFlag.RestrictedMemberAccess , a zestaw dotacji niepubliki członków jest ograniczony do zestawu dotacji obiektu wywołującego lub jego podzbioru. (Zobacz Zabezpieczenia dotyczące odbicia). Aby korzystać z tej funkcji, aplikacja powinna być docelowa .NET Framework 3.5 lub nowsza.

Dotyczy