PropertyInfo.SetValue Método

Definición

Establece el valor de propiedad para un objeto especificado.

Sobrecargas

SetValue(Object, Object)

Establece el valor de propiedad de un objeto especificado.

SetValue(Object, Object, Object[])

Establece el valor de propiedad de un objeto especificado con valores de índice opcionales para las propiedades del índice.

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

Cuando se reemplaza en una clase derivada, establece el valor de propiedad para un objeto especificado que tiene el enlace, el índice y la información específica de la referencia cultural especificados.

SetValue(Object, Object)

Establece el valor de propiedad de un objeto especificado.

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)

Parámetros

obj
Object

Objeto cuyo valor de propiedad se va a establecer.

value
Object

Nuevo valor de propiedad.

Excepciones

No se encuentra el descriptor de acceso set de la propiedad.

o bien

value no se puede convertir al tipo de PropertyType.

El tipo de obj no coincide con el tipo de destino o una propiedad es una propiedad de instancia, pero obj es null.

Nota: En .NET para aplicaciones de la Tienda Windows o la biblioteca de clases portable, detecte Exception en su lugar.

Hubo un intento no válido de obtener acceso a un método privado o protegido dentro de una clase.

Nota: En .NET para aplicaciones de la Tienda Windows o la Biblioteca de clases portable, detecte la excepción de clase base, MemberAccessException, en su lugar.

Error al establecer el valor de la propiedad. La propiedad InnerException indica el motivo del error.

Ejemplos

En el ejemplo siguiente se declara una clase denominada Example con una static (Shared en Visual Basic) y una propiedad de instancia. En el ejemplo se usa el SetValue(Object, Object) método para cambiar los valores de propiedad originales y se muestran los valores originales y 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

Comentarios

La SetValue(Object, Object) sobrecarga establece el valor de una propiedad no indexada. Para determinar si una propiedad está indizada, llame al GetIndexParameters método . Si la matriz resultante tiene 0 elementos (cero), la propiedad no se indexa. Para establecer el valor de una propiedad indizada, llame a la SetValue(Object, Object, Object[]) sobrecarga.

Si el tipo de propiedad de este PropertyInfo objeto es un tipo de valor y value es null, la propiedad se establecerá en el valor predeterminado de ese tipo.

Se trata de un método de conveniencia que llama a la implementación en tiempo de ejecución del método abstractoSetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo), especificando BindingFlags.Default para el BindingFlags parámetro , null para Bindernull , para Object[]y null para CultureInfo.

Para usar el SetValue método , obtenga primero un Type objeto que represente la clase . TypeEn , obtenga el PropertyInfo objeto . Desde el PropertyInfo objeto , llame al SetValue método .

Nota

A partir de .NET Framework 2.0, este método se puede usar para acceder a miembros no públicos si se ha concedido ReflectionPermission al autor de la llamada con la ReflectionPermissionFlag.RestrictedMemberAccess marca y si el conjunto de concesión de los miembros no públicos está restringido al conjunto de concesión del autor de la llamada o a un subconjunto de ellos. (Consulte Consideraciones de seguridad para la reflexión). Para usar esta funcionalidad, la aplicación debe tener como destino .NET Framework 3.5 o posterior.

Se aplica a

SetValue(Object, Object, Object[])

Establece el valor de propiedad de un objeto especificado con valores de índice opcionales para las propiedades del índice.

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

Parámetros

obj
Object

Objeto cuyo valor de propiedad se va a establecer.

value
Object

Nuevo valor de propiedad.

index
Object[]

Valores de índice opcionales para propiedades indizadas. Este valor debe ser null para propiedades no indizadas.

Implementaciones

Excepciones

La matriz index no contiene el tipo de argumentos necesario.

o bien

No se encuentra el descriptor de acceso set de la propiedad.

o bien

value no se puede convertir al tipo de PropertyType.

El objeto no coincide con el tipo de destino o una propiedad es una propiedad de instancia, pero obj es null.

Nota: En .NET para aplicaciones de la Tienda Windows o la biblioteca de clases portable, detecte Exception en su lugar.

El número de parámetros de index no coincide con el número de parámetros que toma la propiedad indexada.

Hubo un intento no válido de obtener acceso a un método privado o protegido dentro de una clase.

Nota: En .NET para aplicaciones de la Tienda Windows o la Biblioteca de clases portable, detecte la excepción de clase base, MemberAccessException, en su lugar.

Error al establecer el valor de la propiedad. Por ejemplo, un valor de índice especificado para una propiedad indizada está fuera del intervalo. La propiedad InnerException indica el motivo del error.

Ejemplos

En el ejemplo siguiente se define una clase denominada TestClass que tiene una propiedad de lectura y escritura denominada Caption. Muestra el valor predeterminado de la Caption propiedad, llama al SetValue método para cambiar el valor de la propiedad y muestra el resultado.

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.

Tenga en cuenta que, dado que la Caption propiedad no es una matriz de parámetros, el index argumento es null.

En el ejemplo siguiente se declara una clase denominada Example con tres propiedades: una static propiedad (Shared en Visual Basic), una propiedad de instancia y una propiedad de instancia indizada. En el ejemplo se usa el SetValue método para cambiar los valores predeterminados de las propiedades y se muestran los valores originales y finales.

El nombre que se usa para buscar una propiedad de instancia indizada con reflexión es diferente en función del idioma y de los atributos aplicados a la propiedad .

  • En Visual Basic, el nombre de la propiedad siempre se usa para buscar la propiedad con reflexión. Puede usar la Default palabra clave para convertir la propiedad en una propiedad indexada predeterminada, en cuyo caso puede omitir el nombre al acceder a la propiedad, como en este ejemplo. También puede usar el nombre de la propiedad.

  • En C#, la propiedad de instancia indizada es una propiedad predeterminada denominada indexador y el nombre nunca se usa al acceder a la propiedad en el código. De forma predeterminada, el nombre de la propiedad es Itemy debe usar ese nombre al buscar la propiedad con reflexión. Puede usar el IndexerNameAttribute atributo para asignar al indexador un nombre diferente. En este ejemplo, el nombre es IndexedInstanceProperty.

  • En C++, el default especificador se puede usar para convertir una propiedad indizada en una propiedad indexada predeterminada (indexador de clase). En ese caso, el nombre de la propiedad de forma predeterminada es Item, y debe usar ese nombre al buscar la propiedad con reflexión, como en este ejemplo. Puede usar el IndexerNameAttribute atributo para asignar al indexador de clases un nombre diferente en la reflexión, pero no puede usar ese nombre para tener acceso a la propiedad en el código. Se tiene acceso a una propiedad indizada que no es un indizador de clase mediante su nombre, tanto en el código como en la reflexión.

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'

Comentarios

Si este PropertyInfo objeto es un tipo de valor y value es null, la propiedad se establecerá en el valor predeterminado de ese tipo.

Para determinar si una propiedad está indizada, use el GetIndexParameters método . Si la matriz resultante tiene 0 elementos (cero), la propiedad no se indexa.

Se trata de un método de conveniencia que llama a la implementación en tiempo de ejecución del método abstracto SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) , especificando BindingFlags.Default para el BindingFlags parámetro , null para Bindery null para CultureInfo.

Para usar el SetValue método , obtenga primero un Type objeto que represente la clase . TypeEn , obtenga .PropertyInfo PropertyInfoEn , use el SetValue método .

Nota

A partir de .NET Framework 2.0, este método se puede usar para acceder a miembros no públicos si se ha concedido ReflectionPermission al autor de la llamada con la ReflectionPermissionFlag.RestrictedMemberAccess marca y si el conjunto de concesión de los miembros no públicos está restringido al conjunto de concesión del autor de la llamada o a un subconjunto de ellos. (Consulte Consideraciones de seguridad para la reflexión). Para usar esta funcionalidad, la aplicación debe tener como destino .NET Framework 3.5 o posterior.

Se aplica a

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

Cuando se reemplaza en una clase derivada, establece el valor de propiedad para un objeto especificado que tiene el enlace, el índice y la información específica de la referencia cultural especificados.

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)

Parámetros

obj
Object

Objeto cuyo valor de propiedad se va a establecer.

value
Object

Nuevo valor de propiedad.

invokeAttr
BindingFlags

Una combinación bit a bit de los miembros de enumeración siguientes que especifican el atributo de invocación: InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty o SetProperty. Debe especificarse un atributo de invocación apropiado. Por ejemplo, para llamar a un miembro estático, establezca la marca Static.

binder
Binder

Objeto que permite el enlace, la conversión de tipos de argumentos, la llamada de miembros y la recuperación de objetos MemberInfo mediante reflexión. Si binder es null, se usa el enlazador predeterminado.

index
Object[]

Valores de índice opcionales para propiedades indizadas. Este valor debe ser null para propiedades no indizadas.

culture
CultureInfo

Referencia cultural a la que se va a adaptar el recurso. Si el recurso no se encuentra el recurso correspondiente a esta referencia cultural, se llamará sucesivamente a Parent para buscar una coincidencia. Si este valor es null, la información específica de la referencia cultural se obtiene de la propiedad CurrentUICulture.

Implementaciones

Excepciones

La matriz index no contiene el tipo de argumentos necesario.

o bien

No se encuentra el descriptor de acceso set de la propiedad.

O bien

value no se puede convertir al tipo de PropertyType.

El objeto no coincide con el tipo de destino o una propiedad es una propiedad de instancia, pero obj es null.

El número de parámetros de index no coincide con el número de parámetros que toma la propiedad indexada.

Hubo un intento no válido de obtener acceso a un método privado o protegido dentro de una clase.

Error al establecer el valor de la propiedad. Por ejemplo, un valor de índice especificado para una propiedad indizada está fuera del intervalo. La propiedad InnerException indica el motivo del error.

Comentarios

Si este PropertyInfo objeto es un tipo de valor y value es null, la propiedad se establecerá en el valor predeterminado de ese tipo.

Para determinar si una propiedad está indizada, use el GetIndexParameters método . Si la matriz resultante tiene 0 elementos (cero), la propiedad no se indexa.

Las restricciones de acceso se omiten para el código de plena confianza. Es decir, se puede tener acceso a constructores privados, métodos, campos y propiedades e invocarse a través de Reflection siempre que el código sea de plena confianza.

Para usar el SetValue método , obtenga primero la clase Type. TypeEn , obtenga .PropertyInfo PropertyInfoEn , use el SetValue método .

Nota

A partir de .NET Framework 2.0, este método se puede usar para acceder a miembros no públicos si se ha concedido ReflectionPermission al autor de la llamada con la ReflectionPermissionFlag.RestrictedMemberAccess marca y si el conjunto de concesión de los miembros no públicos está restringido al conjunto de concesión del autor de la llamada o a un subconjunto de ellos. (Consulte Consideraciones de seguridad para la reflexión). Para usar esta funcionalidad, la aplicación debe tener como destino .NET Framework 3.5 o posterior.

Se aplica a