PropertyInfo.SetValue Méthode

Définition

Définit la valeur de propriété d'un objet spécifié.

Surcharges

SetValue(Object, Object)

Définit la valeur de la propriété d'un objet spécifié.

SetValue(Object, Object, Object[])

Définit la valeur de la propriété d'un objet spécifié avec des valeurs d'index facultatives pour les propriétés de l'index.

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

En cas de substitution dans une classe dérivée, définit la valeur de propriété d'un objet spécifié qui possède la liaison, l'index et les informations propres à la culture spécifiés.

SetValue(Object, Object)

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

Définit la valeur de la propriété d'un objet spécifié.

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ètres

obj
Object

Objet dont la valeur de propriété sera définie.

value
Object

Nouvelle valeur de la propriété.

Exceptions

L’accesseur set de la propriété est introuvable.

- ou -

value ne peut pas être converti dans le type de PropertyType.

Le type de obj ne correspond pas au type cible, ou une propriété est une propriété d’instance alors que obj a la valeur null.

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

Tentative non autorisée d’accéder à une méthode privée ou protégée à l’intérieur d’une classe.

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.

Une erreur s’est produite pendant la définition de la valeur de la propriété. La propriété InnerException indique la raison de l’erreur.

Exemples

L’exemple suivant déclare une classe nommée Example avec une static propriété (Shared en Visual Basic) et une propriété d’instance. L’exemple utilise la SetValue(Object, Object) méthode pour modifier les valeurs de propriété d’origine et affiche les valeurs d’origine et finales.

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

Remarques

La SetValue(Object, Object) surcharge définit la valeur d’une propriété non indexée. Pour déterminer si une propriété est indexée, appelez la GetIndexParameters méthode . Si le tableau résultant a 0 (zéro) éléments, la propriété n’est pas indexée. Pour définir la valeur d’une propriété indexée, appelez la SetValue(Object, Object, Object[]) surcharge.

Si le type de propriété de cet PropertyInfo objet est un type valeur et value est null, la propriété sera définie sur la valeur par défaut pour ce type.

Il s’agit d’une méthode pratique qui appelle l’implémentation d’exécution de la méthode abstraiteSetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo), en spécifiant BindingFlags.Default pour le BindingFlags paramètre , null pour BinderObject[], null et null pour CultureInfo.

Pour utiliser la SetValue méthode, commencez par obtenir un Type objet qui représente la classe . À partir de , Typeobtenez l’objet PropertyInfo . À partir de l’objet PropertyInfo , appelez la SetValue méthode .

Notes

À compter de .NET Framework 2.0, 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, Object[])

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

Définit la valeur de la propriété d'un objet spécifié avec des valeurs d'index facultatives pour les propriétés de l'index.

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ètres

obj
Object

Objet dont la valeur de propriété sera définie.

value
Object

Nouvelle valeur de la propriété.

index
Object[]

Valeurs d'index facultatives pour les propriétés indexées. Cette valeur doit être null pour les propriétés non indexées.

Implémente

Exceptions

Le tableau index ne contient pas le type d’arguments requis.

- ou -

L’accesseur set de la propriété est introuvable.

- ou -

value ne peut pas être converti dans le type de PropertyType.

L’objet ne correspond pas au type cible, ou une propriété est une propriété d’instance mais obj a la valeur null.

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

Le nombre de paramètres dans index ne correspond pas au nombre de paramètres que prend la propriété indexée.

Tentative non autorisée d’accéder à une méthode privée ou protégée à l’intérieur d’une classe.

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.

Une erreur s’est produite pendant la définition de la valeur de la propriété. Par exemple, une valeur d’index spécifiée pour une propriété indexée est hors limites. La propriété InnerException indique la raison de l’erreur.

Exemples

L’exemple suivant définit une classe nommée TestClass qui a une propriété en lecture-écriture nommée Caption. Il affiche la valeur par défaut de la Caption propriété, appelle la SetValue méthode pour modifier la valeur de la propriété et affiche le résultat.

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.

Notez que, comme la Caption propriété n’est pas un tableau de paramètres, l’argument index est null.

L’exemple suivant déclare une classe nommée Example avec trois propriétés : une static propriété (Shared en Visual Basic), une propriété d’instance et une propriété d’instance indexée. L’exemple utilise la SetValue méthode pour modifier les valeurs par défaut des propriétés et affiche les valeurs d’origine et finales.

Le nom utilisé pour rechercher une propriété d’instance indexée avec réflexion est différent selon la langue et les attributs appliqués à la propriété.

  • En Visual Basic, le nom de la propriété est toujours utilisé pour rechercher la propriété avec réflexion. Vous pouvez utiliser le Default mot clé pour faire de la propriété une propriété indexée par défaut, auquel cas vous pouvez omettre le nom lors de l’accès à la propriété, comme dans cet exemple. Vous pouvez également utiliser le nom de la propriété.

  • En C#, la propriété d’instance indexée est une propriété par défaut appelée indexeur, et le nom n’est jamais utilisé lors de l’accès à la propriété dans le code. Par défaut, le nom de la propriété est Item, et vous devez utiliser ce nom lorsque vous recherchez la propriété avec réflexion. Vous pouvez utiliser l’attribut IndexerNameAttribute pour donner un nom différent à l’indexeur. Dans cet exemple, le nom est IndexedInstanceProperty.

  • En C++, le default spécificateur peut être utilisé pour faire d’une propriété indexée une propriété indexée par défaut (indexeur de classe). Dans ce cas, le nom de la propriété par défaut est Item, et vous devez utiliser ce nom lorsque vous recherchez la propriété avec réflexion, comme dans cet exemple. Vous pouvez utiliser l’attribut IndexerNameAttribute pour donner à l’indexeur de classe un nom différent en réflexion, mais vous ne pouvez pas utiliser ce nom pour accéder à la propriété dans le code. Une propriété indexée qui n’est pas un indexeur de classe est accessible à l’aide de son nom, à la fois dans le code et dans la réflexion.

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'

Remarques

Si cet PropertyInfo objet est un type valeur et value est null, la propriété est définie sur la valeur par défaut pour ce type.

Pour déterminer si une propriété est indexée, utilisez la GetIndexParameters méthode . Si le tableau résultant a 0 (zéro) éléments, la propriété n’est pas indexée.

Il s’agit d’une méthode pratique qui appelle l’implémentation d’exécution de la méthode abstraite SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) , en spécifiant BindingFlags.Default pour le BindingFlags paramètre , null pour Binderet null pour CultureInfo.

Pour utiliser la SetValue méthode, commencez par obtenir un Type objet qui représente la classe . À partir de Type, obtenez le PropertyInfo. À partir de , PropertyInfoutilisez la SetValue méthode .

Notes

À compter de .NET Framework 2.0, 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, Object[], CultureInfo)

Source:
PropertyInfo.cs
Source:
PropertyInfo.cs
Source:
PropertyInfo.cs

En cas de substitution dans une classe dérivée, définit la valeur de propriété d'un objet spécifié qui possède la liaison, l'index et les informations propres à la culture spécifiés.

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ètres

obj
Object

Objet dont la valeur de propriété sera définie.

value
Object

Nouvelle valeur de la propriété.

invokeAttr
BindingFlags

Combinaison d'opérations de bits des membres suivants de l'énumération qui spécifie l'attribut d'appel : InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty ou SetProperty. Vous devez spécifier un attribut d'appel approprié. Par exemple, pour appeler un membre statique, définissez l'indicateur Static .

binder
Binder

Objet qui active la liaison, la contrainte de types d'arguments, l'appel des membres et la récupération d'objets MemberInfo par la réflexion. Si binder est null, le binder par défaut est utilisé.

index
Object[]

Valeurs d'index facultatives pour les propriétés indexées. Cette valeur doit être null pour les propriétés non indexées.

culture
CultureInfo

Culture pour laquelle la ressource doit être localisée. Si la ressource n'est pas localisée pour cette culture, la propriété Parent sera appelée pour rechercher une correspondance. Si cette valeur est null, les informations spécifiques à la culture sont obtenues à partir de la propriété CurrentUICulture.

Implémente

Exceptions

Le tableau index ne contient pas le type d’arguments requis.

- ou -

L’accesseur set de la propriété est introuvable.

- ou -

value ne peut pas être converti dans le type de PropertyType.

L’objet ne correspond pas au type cible, ou une propriété est une propriété d’instance mais obj a la valeur null.

Le nombre de paramètres dans index ne correspond pas au nombre de paramètres que prend la propriété indexée.

Tentative non autorisée d’accéder à une méthode privée ou protégée à l’intérieur d’une classe.

Une erreur s’est produite pendant la définition de la valeur de la propriété. Par exemple, une valeur d’index spécifiée pour une propriété indexée est hors limites. La propriété InnerException indique la raison de l’erreur.

Remarques

Si cet PropertyInfo objet est un type valeur et value a la valeur null, la propriété est définie sur la valeur par défaut pour ce type.

Pour déterminer si une propriété est indexée, utilisez la GetIndexParameters méthode . Si le tableau résultant contient 0 (zéro) éléments, la propriété n’est pas indexée.

Les restrictions d’accès sont ignorées pour le code entièrement fiable. Autrement dit, les constructeurs privés, les méthodes, les champs et les propriétés sont accessibles et appelés via Reflection chaque fois que le code est entièrement approuvé.

Pour utiliser la SetValue méthode , commencez par obtenir la classe Type. À partir de Type, obtenez le PropertyInfo. À partir de PropertyInfo, utilisez la SetValue méthode .

Notes

À compter de .NET Framework 2.0, 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 le jeu d’octrois des membres non publics est limité au jeu 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 à