FieldInfo.SetValue Méthode

Définition

Assigne à la valeur spécifiée la valeur du champ de l'objet donné.

Surcharges

SetValue(Object, Object)

Définit la valeur du champ pris en charge par l’objet donné.

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

En cas de substitution dans une classe dérivée, définit la valeur du champ pris en charge par l'objet donné.

SetValue(Object, Object)

Source:
FieldInfo.cs
Source:
FieldInfo.cs
Source:
FieldInfo.cs

Définit la valeur du champ pris en charge par l’objet donné.

public:
 virtual void SetValue(System::Object ^ obj, System::Object ^ value);
public:
 void SetValue(System::Object ^ obj, System::Object ^ value);
public virtual void SetValue (object obj, object value);
public void SetValue (object? obj, object? value);
public void SetValue (object obj, object value);
abstract member SetValue : obj * obj -> unit
override this.SetValue : obj * obj -> unit
member this.SetValue : obj * obj -> unit
Public Overridable Sub SetValue (obj As Object, value As Object)
Public Sub SetValue (obj As Object, value As Object)

Paramètres

obj
Object

Objet dont la valeur de champ sera définie.

value
Object

La valeur à affecter au champ.

Implémente

Exceptions

L’appelant n’est pas autorisé à accéder à ce champ.

Remarque : Dans .NET pour les applications du Windows Store ou la bibliothèque de classes portable, interceptez l’exception de la classe de base, MemberAccessException, à la place.

Le obj paramètre est null et le champ est un champ d’instance.

Remarque : Dans .NET pour les applications du Windows Store ou dans la bibliothèque de classes portable, interceptez Exception plutôt.

Ce champ n'existe pas sur l’objet.

- ou -

Le paramètre value ne peut pas être converti et stocké dans le champ.

Exemples

L’exemple suivant définit la valeur d’un champ, obtient et affiche la valeur, modifie le champ et affiche le résultat.

using namespace System;
using namespace System::Reflection;
using namespace System::Globalization;

public ref class Example
{
private:
   String^ myString;

public:
   Example()
   {
      myString = "Old value";
   }

   property String^ StringProperty 
   {
      String^ get()
      {
         return myString;
      }
   }
};

int main()
{
    Example^ myObject = gcnew Example;
    Type^ myType = Example::typeid;
    FieldInfo^ myFieldInfo = myType->GetField( "myString", 
        BindingFlags::NonPublic | BindingFlags::Instance);
      
    // Display the string before applying SetValue to the field.
    Console::WriteLine( "\nThe field value of myString is \"{0}\".", 
        myFieldInfo->GetValue( myObject ) );
    // Display the SetValue signature used to set the value of a field.
    Console::WriteLine( "Applying SetValue(Object, Object)." );

    // Change the field value using the SetValue method. 
    myFieldInfo->SetValue( myObject, "New value" );     
    // Display the string after applying SetValue to the field.
    Console::WriteLine( "The field value of mystring is \"{0}\".", 
        myFieldInfo->GetValue(myObject));
}
/* This code produces the following output:

The field value of myString is "Old value".
Applying SetValue(Object, Object).
The field value of mystring is "New value".
 */
using System;
using System.Reflection;
using System.Globalization;

public class Example
{
    private string myString;
    public Example()
    {
        myString = "Old value";
    }

    public string StringProperty
    {
        get
        {
            return myString;
        }
    }
}

public class FieldInfo_SetValue
{
    public static void Main()
    {
        Example myObject = new Example();
        Type myType = typeof(Example);
        FieldInfo myFieldInfo = myType.GetField("myString",
            BindingFlags.NonPublic | BindingFlags.Instance);

        // Display the string before applying SetValue to the field.
        Console.WriteLine( "\nThe field value of myString is \"{0}\".",
        myFieldInfo.GetValue(myObject));
        // Display the SetValue signature used to set the value of a field.
        Console.WriteLine( "Applying SetValue(Object, Object).");

        // Change the field value using the SetValue method.
        myFieldInfo.SetValue(myObject, "New value");
        // Display the string after applying SetValue to the field.
        Console.WriteLine( "The field value of mystring is \"{0}\".",
            myFieldInfo.GetValue(myObject));
    }
}

/* This code example produces the following output:

The field value of myString is "Old value".
Applying SetValue(Object, Object).
The field value of mystring is "New value".
 */
Imports System.Reflection
Imports System.Globalization

Public Class Example
   Private myString As String
   
   Public Sub New()
      myString = "Old value"
   End Sub 
   
   ReadOnly Property StringProperty() As String
      Get
         Return myString
      End Get
   End Property
End Class 


Public Module FieldInfo_SetValue
   
   Sub Main()

        Dim myObject As New Example()
        Dim myType As Type = GetType(Example)
        Dim myFieldInfo As FieldInfo = myType.GetField("myString", _
           BindingFlags.NonPublic Or BindingFlags.Instance)

        ' Display the string before applying SetValue to the field.
        Console.WriteLine(vbCrLf & "The field value of myString is ""{0}"".", _
            myFieldInfo.GetValue(myObject))
        ' Display the SetValue signature used to set the value of a field.
        Console.WriteLine("Applying SetValue(Object, Object).")

        ' Change the field value using the SetValue method. 
        myFieldInfo.SetValue(myObject, "New value")
        ' Display the string after applying SetValue to the field.
        Console.WriteLine("The field value of mystring is ""{0}"".", _
            myFieldInfo.GetValue(myObject))

    End Sub 
End Module

' This code example produces the following output:
' The field value of myString is "Old value".
' Applying SetValue(Object, Object).
' The field value of mystring is "New value".

Remarques

Cette méthode est affectée value au champ reflété par cette instance sur l’objet obj. Si le champ est statique, obj est ignoré. Pour les champs non statiques, obj doit être un instance d’une classe qui hérite ou déclare le champ. La nouvelle valeur est passée en tant que Object. Par exemple, si le type du champ est Boolean, une instance de Object avec la valeur booléenne appropriée est passée. Avant de définir la valeur, SetValue vérifiez si l’utilisateur dispose d’une autorisation d’accès. Cette dernière méthode est une méthode pratique pour appeler la méthode suivante SetValue .

Cette méthode ne peut pas être utilisée pour définir de manière fiable les valeurs des champs statiques et init uniquement (readonly en C#). Dans .NET Core 3.0 et versions ultérieures, une exception est levée si vous tentez de définir une valeur sur un champ statique, init uniquement.

Notes

Le code entièrement approuvé dispose des autorisations nécessaires pour accéder et appeler des constructeurs, des méthodes, des champs et des propriétés privés à l’aide de la réflexion.

Notes

À compter du .NET Framework 2.0 Service Pack 1, cette méthode peut être utilisée pour accéder aux membres non publics si l’appelant a reçu ReflectionPermission l’indicateur ReflectionPermissionFlag.RestrictedMemberAccess et si l’ensemble d’octrois des membres non publics est limité à l’ensemble d’octrois de l’appelant ou à un sous-ensemble de celui-ci. (Consultez Considérations relatives à la sécurité pour la réflexion.)

Pour utiliser cette fonctionnalité, votre application doit cibler .NET Framework 3.5 ou version ultérieure.

S’applique à

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

Source:
FieldInfo.cs
Source:
FieldInfo.cs
Source:
FieldInfo.cs

En cas de substitution dans une classe dérivée, définit la valeur du champ pris en charge par l'objet donné.

public:
 abstract void SetValue(System::Object ^ obj, System::Object ^ value, System::Reflection::BindingFlags invokeAttr, System::Reflection::Binder ^ binder, System::Globalization::CultureInfo ^ culture);
public abstract void SetValue (object? obj, object? value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder? binder, System.Globalization.CultureInfo? culture);
public abstract void SetValue (object obj, object value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Globalization.CultureInfo culture);
abstract member SetValue : obj * obj * System.Reflection.BindingFlags * System.Reflection.Binder * System.Globalization.CultureInfo -> unit
Public MustOverride Sub SetValue (obj As Object, value As Object, invokeAttr As BindingFlags, binder As Binder, culture As CultureInfo)

Paramètres

obj
Object

Objet dont la valeur de champ sera définie.

value
Object

La valeur à affecter au champ.

invokeAttr
BindingFlags

Champ de Binder qui spécifie le type de liaison requis (par exemple, Binder.CreateInstance ou Binder.ExactBinding).

binder
Binder

Jeu de propriétés qui active la liaison, la contrainte des types d'arguments, ainsi que l'appel des membres à l'aide de la réflexion. Si binder est null, Binder.DefaultBinding est utilisé.

culture
CultureInfo

Préférences logicielles d'une culture spécifique.

Implémente

Exceptions

L’appelant n’est pas autorisé à accéder à ce champ.

Le obj paramètre est null et le champ est un champ d’instance.

Ce champ n'existe pas sur l’objet.

- ou -

Le paramètre value ne peut pas être converti et stocké dans le champ.

Remarques

Cette méthode est affectée value au champ reflété par cette instance sur obj. Si le champ est statique, obj est ignoré. Pour les champs non statiques, obj doit être un instance d’une classe qui hérite ou déclare le champ. La nouvelle valeur est passée en tant que Object. Par exemple, si le type du champ est Boolean, un instance de Object avec la valeur booléenne appropriée est passé. Avant de définir la valeur, SetValue vérifiez si l’utilisateur dispose d’une autorisation d’accès.

Cette méthode ne peut pas être utilisée pour définir de manière fiable les valeurs des champs statiques et init uniquement (readonly en C#). Dans .NET Core 3.0 et versions ultérieures, une exception est levée si vous tentez de définir une valeur sur un champ statique, init uniquement.

Notes

Le code entièrement approuvé dispose des autorisations nécessaires pour accéder et appeler des constructeurs, des méthodes, des champs et des propriétés privés à l’aide de la réflexion.

Notes

À compter du .NET Framework 2.0 Service Pack 1, cette méthode peut être utilisée pour accéder aux membres non publics si l’appelant a reçu ReflectionPermission l’indicateur ReflectionPermissionFlag.RestrictedMemberAccess et si l’ensemble d’octrois des membres non publics est limité à l’ensemble d’octrois de l’appelant ou à un sous-ensemble de celui-ci. (Consultez Considérations relatives à la sécurité pour la réflexion.)

Pour utiliser cette fonctionnalité, votre application doit cibler .NET Framework 3.5 ou version ultérieure.

S’applique à