Compartilhar via


PropertyInfo.SetValue Método

Definição

Define o valor da propriedade de um objeto especificado.

Sobrecargas

Nome Description
SetValue(Object, Object)

Define o valor da propriedade de um objeto especificado.

SetValue(Object, Object, Object[])

Define o valor da propriedade de um objeto especificado com valores de índice opcionais para propriedades de índice.

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

Quando substituído em uma classe derivada, define o valor da propriedade para um objeto especificado que tem as informações específicas de associação, índice e cultura especificadas.

SetValue(Object, Object)

Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs

Define o valor da propriedade de um 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

O objeto cujo valor de propriedade será definido.

value
Object

O novo valor da propriedade.

Exceções

O acessador da set propriedade não foi encontrado.

- ou -

value não pode ser convertido no tipo de PropertyType.

O tipo de não corresponde ao tipo de obj destino ou uma propriedade é uma propriedade de instância, mas obj é null.

Houve uma tentativa ilegal de acessar um método privado ou protegido dentro de uma classe.

Erro ao definir o valor da propriedade. A InnerException propriedade indica o motivo do erro.

Exemplos

O exemplo a seguir declara uma classe chamada Example com um static (Shared em Visual Basic) e uma propriedade de instância. O exemplo usa o SetValue(Object, Object) método para alterar os valores de propriedade originais e exibe os valores originais e finais.

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

Comentários

A SetValue(Object, Object) sobrecarga define o valor de uma propriedade não indexada. Para determinar se uma propriedade é indexada, chame o GetIndexParameters método. Se a matriz resultante tiver 0 (zero), a propriedade não será indexada. Para definir o valor de uma propriedade indexada, chame a SetValue(Object, Object, Object[]) sobrecarga.

Se o tipo de propriedade desse PropertyInfo objeto for um tipo de valor e value for null, a propriedade será definida como o valor padrão desse tipo.

Esse é um método de conveniência que chama a implementação de runtime do método abstrato SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) , especificando BindingFlags.Default para o BindingFlags parâmetro, null para Binder, null para Object[]e null para CultureInfo.

Para usar o SetValue método, primeiro obtenha um Type objeto que represente a classe. TypeNo objeto , obtenha o PropertyInfo objeto. PropertyInfo No objeto, chame o SetValue método.

Observação

Esse método pode ser usado para acessar membros não públicos se o chamador tiver sido concedido ReflectionPermission com o ReflectionPermissionFlag.RestrictedMemberAccess sinalizador e se o conjunto de concessões dos membros não públicos estiver restrito ao conjunto de concessões do chamador ou a um subconjunto dele. (Consulte Seções de segurança para reflexão.) Para usar essa funcionalidade, seu aplicativo deve ser direcionado .NET Framework 3.5 ou posterior.

Aplica-se a

SetValue(Object, Object, Object[])

Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs

Define o valor da propriedade de um objeto especificado com valores de índice opcionais para propriedades de í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

O objeto cujo valor de propriedade será definido.

value
Object

O novo valor da propriedade.

index
Object[]

Valores de índice opcionais para propriedades indexadas. Esse valor deve ser null para propriedades não indexadas.

Implementações

Exceções

A index matriz não contém o tipo de argumentos necessários.

- ou -

O acessador da set propriedade não foi encontrado.

- ou -

value não pode ser convertido no tipo de PropertyType.

O objeto não corresponde ao tipo de destino ou uma propriedade é uma propriedade de instância, mas obj é null.

O número de parâmetros em index não corresponde ao número de parâmetros que a propriedade indexada usa.

Houve uma tentativa ilegal de acessar um método privado ou protegido dentro de uma classe.

Erro ao definir o valor da propriedade. Por exemplo, um valor de índice especificado para uma propriedade indexada está fora do intervalo. A InnerException propriedade indica o motivo do erro.

Exemplos

O exemplo a seguir define uma classe nomeada TestClass que tem uma propriedade de leitura/gravação chamada Caption. Ele exibe o valor padrão da Caption propriedade, chama o SetValue método para alterar o valor da propriedade e exibe o resultado.

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.

Observe que, como a Caption propriedade não é uma matriz de parâmetros, o index argumento é null.

O exemplo a seguir declara uma classe chamada Example com três propriedades: uma propriedade static (Shared em Visual Basic), uma propriedade de instância e uma propriedade de instância indexada. O exemplo usa o SetValue método para alterar os valores padrão das propriedades e exibe os valores originais e finais.

O nome usado para pesquisar uma propriedade de instância indexada com reflexão é diferente dependendo do idioma e dos atributos aplicados à propriedade.

  • Em Visual Basic, o nome da propriedade é sempre usado para pesquisar a propriedade com reflexão. Você pode usar a Default palavra-chave para tornar a propriedade uma propriedade indexada padrão, nesse caso, você pode omitir o nome ao acessar a propriedade, como neste exemplo. Você também pode usar o nome da propriedade.

  • Em C#, a propriedade de instância indexada é uma propriedade padrão chamada indexador e o nome nunca é usado ao acessar a propriedade no código. Por padrão, o nome da propriedade é Item, e você deve usar esse nome quando pesquisar a propriedade com reflexão. Você pode usar o IndexerNameAttribute atributo para dar ao indexador um nome diferente. Neste exemplo, o 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'

Comentários

Se esse PropertyInfo objeto for um tipo de valor e value for null, a propriedade será definida como o valor padrão para esse tipo.

Para determinar se uma propriedade é indexada, use o GetIndexParameters método. Se a matriz resultante tiver 0 (zero), a propriedade não será indexada.

Esse é um método de conveniência que chama a implementação de runtime do método abstrato SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) , especificando BindingFlags.Default para o BindingFlags parâmetro, null para Bindere null para CultureInfo.

Para usar o SetValue método, primeiro obtenha um Type objeto que represente a classe. TypeDo .get the PropertyInfo. PropertyInfoNo método , use o SetValue método.

Observação

No .NET Framework, esse método poderá ser usado para acessar membros não públicos se o chamador tiver recebido ReflectionPermission com o sinalizador ReflectionPermissionFlag.RestrictedMemberAccess e se o conjunto de concessões dos membros não públicos estiver restrito ao conjunto de concessões do chamador ou a um subconjunto dele. (Consulte Seções de segurança para reflexão.) Para usar essa funcionalidade, seu aplicativo deve ser direcionado .NET Framework 3.5 ou posterior.

Aplica-se a

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

Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs
Origem:
PropertyInfo.cs

Quando substituído em uma classe derivada, define o valor da propriedade para um objeto especificado que tem as informações específicas de associação, índice e cultura especificadas.

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

O objeto cujo valor de propriedade será definido.

value
Object

O novo valor da propriedade.

invokeAttr
BindingFlags

Uma combinação bit a bit dos seguintes membros de enumeração que especificam o atributo de invocação: InvokeMethod, , CreateInstance, Static, GetField, SetField, GetPropertyou SetProperty. Você deve especificar um atributo de invocação adequado. Por exemplo, para invocar um membro estático, defina o Static sinalizador.

binder
Binder

Um objeto que permite a associação, a coerção de tipos de argumento, a invocação de membros e a recuperação de objetos por meio da MemberInfo reflexão. Se binder for null, o associador padrão será usado.

index
Object[]

Valores de índice opcionais para propriedades indexadas. Esse valor deve ser null para propriedades não indexadas.

culture
CultureInfo

A cultura para a qual o recurso deve ser localizado. Se o recurso não estiver localizado para essa cultura, a Parent propriedade será chamada sucessivamente em busca de uma correspondência. Se esse valor for null, as informações específicas da cultura serão obtidas da CurrentUICulture propriedade.

Implementações

Exceções

A index matriz não contém o tipo de argumentos necessários.

- ou -

O acessador da set propriedade não foi encontrado.

- ou -

value não pode ser convertido no tipo de PropertyType.

O objeto não corresponde ao tipo de destino ou uma propriedade é uma propriedade de instância, mas obj é null.

O número de parâmetros em index não corresponde ao número de parâmetros que a propriedade indexada usa.

Houve uma tentativa ilegal de acessar um método privado ou protegido dentro de uma classe.

Erro ao definir o valor da propriedade. Por exemplo, um valor de índice especificado para uma propriedade indexada está fora do intervalo. A InnerException propriedade indica o motivo do erro.

Comentários

Se esse PropertyInfo objeto for um tipo de valor e value for null, a propriedade será definida como o valor padrão para esse tipo.

Para determinar se uma propriedade é indexada, use o GetIndexParameters método. Se a matriz resultante tiver 0 (zero), a propriedade não será indexada.

As restrições de acesso são ignoradas para código totalmente confiável. Ou seja, construtores privados, métodos, campos e propriedades podem ser acessados e invocados via Reflexão sempre que o código for totalmente confiável.

Para usar o SetValue método, primeiro obtenha a classe Type. TypeDo .get the PropertyInfo. PropertyInfoNo método , use o SetValue método.

Observação

Esse método pode ser usado para acessar membros não públicos se o chamador tiver sido concedido ReflectionPermission com o ReflectionPermissionFlag.RestrictedMemberAccess sinalizador e se o conjunto de concessões dos membros não públicos estiver restrito ao conjunto de concessões do chamador ou a um subconjunto dele. (Consulte Seções de segurança para reflexão.) Para usar essa funcionalidade, seu aplicativo deve ser direcionado .NET Framework 3.5 ou posterior.

Aplica-se a