Condividi tramite


PropertyInfo.SetValue Metodo

Definizione

Imposta il valore della proprietà per un oggetto specificato.

Overload

Nome Descrizione
SetValue(Object, Object)

Imposta il valore della proprietà di un oggetto specificato.

SetValue(Object, Object, Object[])

Imposta il valore della proprietà di un oggetto specificato con valori di indice facoltativi per le proprietà dell'indice.

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

In caso di override in una classe derivata, imposta il valore della proprietà per un oggetto specificato con le informazioni specifiche dell'associazione, dell'indice e delle impostazioni cultura specificate.

SetValue(Object, Object)

Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs

Imposta il valore della proprietà di un oggetto specificato.

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)

Parametri

obj
Object

Oggetto il cui valore della proprietà verrà impostato.

value
Object

Nuovo valore della proprietà.

Eccezioni

La funzione di accesso della set proprietà non viene trovata.

oppure

value non può essere convertito nel tipo di PropertyType.

Il tipo di non corrisponde al tipo di destinazione o una proprietà è una proprietà di obj istanza, ma obj è null.

Si è verificato un tentativo non valido di accedere a un metodo privato o protetto all'interno di una classe.

Errore durante l'impostazione del valore della proprietà. La InnerException proprietà indica il motivo dell'errore.

Esempio

Nell'esempio seguente viene dichiarata una classe denominata Example con una static (Shared in Visual Basic) e una proprietà dell'istanza. Nell'esempio viene utilizzato il SetValue(Object, Object) metodo per modificare i valori originali delle proprietà e vengono visualizzati i valori originali e finali.

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

Commenti

L'overload SetValue(Object, Object) imposta il valore di una proprietà non indicizzata. Per determinare se una proprietà è indicizzata, chiamare il GetIndexParameters metodo . Se la matrice risultante ha 0 (zero), la proprietà non viene indicizzata. Per impostare il valore di una proprietà indicizzata, chiamare l'overload SetValue(Object, Object, Object[]) .

Se il tipo di proprietà di questo PropertyInfo oggetto è un tipo valore e value è null, la proprietà verrà impostata sul valore predefinito per tale tipo.

Si tratta di un metodo pratico che chiama l'implementazione di runtime del metodo astrattoSetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo), specificando BindingFlags.Default per il BindingFlags parametro , null per BindernullObject[]e null per CultureInfo.

Per usare il SetValue metodo , ottenere innanzitutto un Type oggetto che rappresenta la classe . TypeDa ottenere l'oggetto PropertyInfo . Dall'oggetto PropertyInfo chiamare il SetValue metodo .

Annotazioni

Questo metodo può essere usato per accedere a membri non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei membri non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Security Considerations for Reflection.) Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.

Si applica a

SetValue(Object, Object, Object[])

Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs

Imposta il valore della proprietà di un oggetto specificato con valori di indice facoltativi per le proprietà dell'indice.

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

Parametri

obj
Object

Oggetto il cui valore della proprietà verrà impostato.

value
Object

Nuovo valore della proprietà.

index
Object[]

Valori di indice facoltativi per le proprietà indicizzate. Questo valore deve essere null per le proprietà non indicizzate.

Implementazioni

Eccezioni

La index matrice non contiene il tipo di argomenti necessari.

oppure

La funzione di accesso della set proprietà non viene trovata.

oppure

value non può essere convertito nel tipo di PropertyType.

L'oggetto non corrisponde al tipo di destinazione o una proprietà è una proprietà dell'istanza, ma obj è null.

Il numero di parametri in index non corrisponde al numero di parametri accettati dalla proprietà indicizzata.

Si è verificato un tentativo non valido di accedere a un metodo privato o protetto all'interno di una classe.

Errore durante l'impostazione del valore della proprietà. Ad esempio, un valore di indice specificato per una proprietà indicizzata non è compreso nell'intervallo. La InnerException proprietà indica il motivo dell'errore.

Esempio

Nell'esempio seguente viene definita una classe denominata TestClass con una proprietà di lettura/scrittura denominata Caption. Visualizza il valore predefinito della Caption proprietà, chiama il SetValue metodo per modificare il valore della proprietà e visualizza il risultato.

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.

Si noti che, poiché la Caption proprietà non è una matrice di parametri, l'argomento index è null.

Nell'esempio seguente viene dichiarata una classe denominata Example con tre proprietà: una proprietà static (Shared in Visual Basic), una proprietà dell'istanza e una proprietà dell'istanza indicizzata. Nell'esempio viene utilizzato il SetValue metodo per modificare i valori predefiniti delle proprietà e visualizzare i valori originali e finali.

Il nome utilizzato per cercare una proprietà di istanza indicizzata con reflection è diverso a seconda della lingua e degli attributi applicati alla proprietà.

  • In Visual Basic, il nome della proprietà viene sempre usato per cercare la proprietà con reflection. È possibile usare la Default parola chiave per impostare la proprietà su una proprietà indicizzata predefinita, nel qual caso è possibile omettere il nome durante l'accesso alla proprietà, come in questo esempio. È anche possibile usare il nome della proprietà.

  • In C# la proprietà dell'istanza indicizzata è una proprietà predefinita denominata indicizzatore e il nome non viene mai usato quando si accede alla proprietà nel codice. Per impostazione predefinita, il nome della proprietà è Iteme è necessario usare tale nome quando si cerca la proprietà con reflection. È possibile usare l'attributo per assegnare all'indicizzatore IndexerNameAttribute un nome diverso. In questo esempio il nome è 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'

Commenti

Se questo PropertyInfo oggetto è un tipo di valore e value è null, la proprietà verrà impostata sul valore predefinito per tale tipo.

Per determinare se una proprietà è indicizzata, utilizzare il GetIndexParameters metodo . Se la matrice risultante ha 0 (zero), la proprietà non viene indicizzata.

Si tratta di un metodo pratico che chiama l'implementazione di runtime del metodo astratto SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) , specificando BindingFlags.Default per il BindingFlags parametro , null per Bindere null per CultureInfo.

Per usare il SetValue metodo , ottenere innanzitutto un Type oggetto che rappresenta la classe . TypeDa ottenere .PropertyInfo PropertyInfoDa usare il SetValue metodo .

Annotazioni

In .NET Framework questo metodo può essere usato per accedere a membri non pubblici se al chiamante è stato concesso ReflectionPermission con il flag ReflectionPermissionFlag.RestrictedMemberAccess e se il set di concessioni dei membri non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Security Considerations for Reflection.) Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.

Si applica a

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

Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs
Origine:
PropertyInfo.cs

In caso di override in una classe derivata, imposta il valore della proprietà per un oggetto specificato con le informazioni specifiche dell'associazione, dell'indice e delle impostazioni cultura specificate.

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)

Parametri

obj
Object

Oggetto il cui valore della proprietà verrà impostato.

value
Object

Nuovo valore della proprietà.

invokeAttr
BindingFlags

Combinazione bit per bit dei membri di enumerazione seguenti che specificano l'attributo di chiamata: InvokeMethod, SetFieldCreateInstanceGetFieldStatic, GetProperty, o .SetProperty È necessario specificare un attributo di chiamata appropriato. Ad esempio, per richiamare un membro statico, impostare il Static flag .

binder
Binder

Oggetto che consente l'associazione, la coercizione dei tipi di argomento, la chiamata di membri e il recupero di MemberInfo oggetti tramite reflection. Se binder è null, viene usato il gestore di associazione predefinito.

index
Object[]

Valori di indice facoltativi per le proprietà indicizzate. Questo valore deve essere null per le proprietà non indicizzate.

culture
CultureInfo

Impostazioni cultura per cui la risorsa deve essere localizzata. Se la risorsa non è localizzata per queste impostazioni cultura, la Parent proprietà verrà chiamata successivamente nella ricerca di una corrispondenza. Se questo valore è null, le informazioni specifiche delle CurrentUICulture impostazioni cultura vengono ottenute dalla proprietà .

Implementazioni

Eccezioni

La index matrice non contiene il tipo di argomenti necessari.

oppure

La funzione di accesso della set proprietà non viene trovata.

oppure

value non può essere convertito nel tipo di PropertyType.

L'oggetto non corrisponde al tipo di destinazione o una proprietà è una proprietà dell'istanza, ma obj è null.

Il numero di parametri in index non corrisponde al numero di parametri accettati dalla proprietà indicizzata.

Si è verificato un tentativo non valido di accedere a un metodo privato o protetto all'interno di una classe.

Errore durante l'impostazione del valore della proprietà. Ad esempio, un valore di indice specificato per una proprietà indicizzata non è compreso nell'intervallo. La InnerException proprietà indica il motivo dell'errore.

Commenti

Se questo PropertyInfo oggetto è un tipo di valore e value è null, la proprietà verrà impostata sul valore predefinito per tale tipo.

Per determinare se una proprietà è indicizzata, utilizzare il GetIndexParameters metodo . Se la matrice risultante ha 0 (zero), la proprietà non viene indicizzata.

Le restrizioni di accesso vengono ignorate per il codice completamente attendibile. Ovvero, i costruttori privati, i metodi, i campi e le proprietà possono essere accessibili e richiamati tramite Reflection ogni volta che il codice è completamente attendibile.

Per usare il SetValue metodo , ottenere prima di tutto la classe Type. TypeDa ottenere .PropertyInfo PropertyInfoDa usare il SetValue metodo .

Annotazioni

Questo metodo può essere usato per accedere a membri non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei membri non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Security Considerations for Reflection.) Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.

Si applica a