PropertyInfo.SetValue Metodo

Definizione

Imposta il valore della proprietà per un oggetto specificato.

Overload

SetValue(Object, Object)

Imposta il valore della proprietà di un oggetto specificato.

SetValue(Object, Object, Object[])

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

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

Quando ne viene eseguito l'override in una classe derivata, imposta il valore della proprietà per un oggetto specificato con il binding, l'indice e le informazioni specifiche delle impostazioni cultura indicati.

SetValue(Object, Object)

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

Imposta il valore della proprietà di un oggetto specificato.

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

Parametri

obj
Object

Oggetto di cui verrà impostato il valore della proprietà.

value
Object

Nuovo valore della proprietà.

Eccezioni

La funzione di accesso set della proprietà non è stata trovata.

-oppure-

Non è possibile convertire value nel tipo di PropertyType.

Il tipo di obj non corrisponde al tipo di destinazione oppure una proprietà è una proprietà dell'istanza ma obj è null.

Nota: in .NET per le app di Windows Store o nella libreria di classi portabile intercettare Exception .

È stato effettuato un tentativo non valido di accedere a un metodo privato o protetto all'interno di una classe.

Nota: in .NET per le app di Windows Store o nella libreria di classi portabile intercettare invece l'eccezione della classe base, MemberAccessException, .

Si è verificato un errore durante l'impostazione del valore della proprietà. La causa di questo errore è indicata dalla proprietà InnerException.

Esempio

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

using 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

Commenti

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

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

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

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

Nota

A partire da .NET Framework 2.0, questo metodo può essere usato per accedere a membri non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei membri non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per la reflection. Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.

Si applica a

SetValue(Object, Object, Object[])

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

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

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

Parametri

obj
Object

Oggetto di cui verrà impostato il valore della proprietà.

value
Object

Nuovo valore della proprietà.

index
Object[]

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

Implementazioni

Eccezioni

La matrice index non contiene il tipo di argomenti necessari.

-oppure-

La funzione di accesso set della proprietà non è stata trovata.

-oppure-

Non è possibile convertire value nel tipo di PropertyType.

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

Nota: in .NET per le app di Windows Store o nella libreria di classi portabile intercettare Exception .

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

È stato effettuato un tentativo non valido di accedere a un metodo privato o protetto all'interno di una classe.

Nota: in .NET per le app di Windows Store o nella libreria di classi portabile intercettare invece l'eccezione della classe base, MemberAccessException, .

Si è verificato un errore durante l'impostazione del valore della proprietà. Ad esempio, un valore di indice specificato per una proprietà indicizzata non è compreso nell'intervallo. La causa di questo errore è indicata dalla proprietà InnerException.

Esempio

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

using 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.

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

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

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

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

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

  • In C++, l'identificatore default può essere usato per rendere una proprietà indicizzata una proprietà indicizzata predefinita (indicizzatore di classi). In tal caso, il nome della proprietà per impostazione predefinita è Iteme è necessario usare tale nome quando si cerca la proprietà con reflection, come in questo esempio. È possibile usare l'attributo per assegnare all'indicizzatore IndexerNameAttribute di classe un nome diverso nella reflection, ma non è possibile usare tale nome per accedere alla proprietà nel codice. È possibile accedere a una proprietà indicizzata che non è un indicizzatore di classi usando il relativo nome, sia nel codice che nella reflection.

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'

Commenti

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

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

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

Per usare il SetValue metodo , ottenere prima di tutto un Type oggetto che rappresenta la classe . Da ottenere l'oggetto TypePropertyInfo. PropertyInfoDa , usare il SetValue metodo .

Nota

A partire da .NET Framework 2.0, questo metodo può essere usato per accedere a membri non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessioni dei membri non pubblici è limitato al set di concessioni del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per la reflection. Per usare questa funzionalità, l'applicazione deve avere come destinazione .NET Framework 3.5 o versione successiva.

Si applica a

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

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

Quando ne viene eseguito l'override in una classe derivata, imposta il valore della proprietà per un oggetto specificato con il binding, l'indice e le informazioni specifiche delle impostazioni cultura indicati.

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

Parametri

obj
Object

Oggetto di cui verrà impostato il valore della proprietà.

value
Object

Nuovo valore della proprietà.

invokeAttr
BindingFlags

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

binder
Binder

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

index
Object[]

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

culture
CultureInfo

Impostazioni cultura in base alle quali deve essere localizzata la risorsa. Se la risorsa non viene localizzata con queste impostazioni cultura, la proprietà Parent verrà successivamente chiamata in cerca di una corrispondenza. Se questo valore è null, le informazioni specifiche delle impostazioni cultura vengono ottenute dalla proprietà CurrentUICulture.

Implementazioni

Eccezioni

La matrice index non contiene il tipo di argomenti necessari.

-oppure-

La funzione di accesso set della proprietà non è stata trovata.

-oppure-

Non è possibile convertire value nel tipo di PropertyType.

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

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

È stato effettuato un tentativo non valido di accedere a un metodo privato o protetto all'interno di una classe.

Si è verificato un errore durante l'impostazione del valore della proprietà. Ad esempio, un valore di indice specificato per una proprietà indicizzata non è compreso nell'intervallo. La causa di questo errore è indicata dalla proprietà InnerException.

Commenti

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

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

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

Per usare il metodo, ottenere prima di tutto SetValue la classe Type. Dall'oggetto , ottenere l'oggetto TypePropertyInfo. PropertyInfoDa , usare il SetValue metodo .

Nota

A partire da .NET Framework 2.0, questo metodo può essere usato per accedere a membri non pubblici se il chiamante è stato concesso ReflectionPermission con il ReflectionPermissionFlag.RestrictedMemberAccess flag e se il set di concessione dei membri non pubblici è limitato al set di concessione del chiamante o a un subset. Vedere Considerazioni sulla sicurezza per Reflection. Per usare questa funzionalità, l'applicazione deve essere di destinazione .NET Framework 3.5 o successiva.

Si applica a