PropertyInfo.SetValue Yöntem

Tanım

Belirtilen nesne için özellik değerini ayarlar.

Aşırı Yüklemeler

SetValue(Object, Object)

Belirtilen nesnenin özellik değerini ayarlar.

SetValue(Object, Object, Object[])

Dizin özellikleri için isteğe bağlı dizin değerleriyle belirtilen bir nesnenin özellik değerini ayarlar.

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

Türetilmiş bir sınıfta geçersiz kılındığında, belirtilen bağlama, dizin ve kültüre özgü bilgilere sahip belirtilen nesnenin özellik değerini ayarlar.

SetValue(Object, Object)

Kaynak:
PropertyInfo.cs
Kaynak:
PropertyInfo.cs
Kaynak:
PropertyInfo.cs

Belirtilen nesnenin özellik değerini ayarlar.

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)

Parametreler

obj
Object

Özellik değeri ayarlanacak nesne.

value
Object

Yeni özellik değeri.

Özel durumlar

Özelliğin set erişimcisi bulunamadı.

-veya-

value türüne PropertyTypedönüştürülemez.

türü obj hedef türüyle eşleşmiyor veya bir özellik bir örnek özelliğidir ancak obj şeklindedir null.

Not: Windows Mağazası uygulamaları için .NET'te veya Taşınabilir Sınıf Kitaplığı'nda bunun yerine yakalayın Exception .

Bir sınıfın içinde özel veya korumalı bir yönteme erişmeye yönelik yasadışı bir girişim vardı.

Not: Windows Mağazası uygulamaları için .NET'te veya Taşınabilir Sınıf Kitaplığı'nda bunun yerine temel sınıf özel durumunu MemberAccessExceptionyakalayın.

Özellik değeri ayarlanırken bir hata oluştu. InnerException özelliği hatanın nedenini gösterir.

Örnekler

Aşağıdaki örnekte, bir (Shared Visual Basic'te) ve bir örnek özelliğiyle static adlı Example bir sınıf bildirilmiştir. Örnek, özgün özellik değerlerini değiştirmek için yöntemini kullanır SetValue(Object, Object) ve özgün ve son değerleri görüntüler.

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

Açıklamalar

Aşırı SetValue(Object, Object) yükleme, dizine alınan olmayan bir özelliğin değerini ayarlar. Bir özelliğin dizine eklenmiş olup olmadığını belirlemek için yöntemini çağırın GetIndexParameters . Sonuçta elde edilen dizide 0 (sıfır) öğe varsa, özellik dizine alınmaz. Dizine alınan özelliğin değerini ayarlamak için aşırı yüklemeyi çağırın SetValue(Object, Object, Object[]) .

Bu PropertyInfo nesnenin özellik türü bir değer türüyse ve value ise null, özellik bu tür için varsayılan değere ayarlanır.

Bu, soyut SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) yöntemin çalışma zamanı uygulamasını çağıranBindingFlags.Default, parametresi için BindingFlags , null için BinderObject[]null ve nullCultureInfoiçin öğesini belirten bir kolaylık yöntemidir.

yöntemini kullanmak SetValue için önce sınıfını temsil eden bir Type nesne alın. öğesinden Typenesnesini alın PropertyInfo . nesnesinden PropertyInfo yöntemini çağırın SetValue .

Not

.NET Framework 2.0'dan başlayarak, çağıranın ReflectionPermission bayrağı verilmişse ve ortak olmayan üyelerin izin kümesi çağıranın izin kümesiyle veya bunun bir alt kümesiyle ReflectionPermissionFlag.RestrictedMemberAccess kısıtlanmışsa, bu yöntem ortak olmayan üyelere erişmek için kullanılabilir. (Bkz. Yansıma için GüvenlikLe İlgili Dikkat Edilmesi Gerekenler.) Bu işlevi kullanmak için uygulamanızın 3.5 veya sonraki .NET Framework hedeflemesi gerekir.

Şunlara uygulanır

SetValue(Object, Object, Object[])

Kaynak:
PropertyInfo.cs
Kaynak:
PropertyInfo.cs
Kaynak:
PropertyInfo.cs

Dizin özellikleri için isteğe bağlı dizin değerleriyle belirtilen bir nesnenin özellik değerini ayarlar.

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

Parametreler

obj
Object

Özellik değeri ayarlanacak nesne.

value
Object

Yeni özellik değeri.

index
Object[]

Dizine alınan özellikler için isteğe bağlı dizin değerleri. Bu değer dizine alınamayan özellikler için olmalıdır null .

Uygulamalar

Özel durumlar

Dizi index , gereken bağımsız değişkenlerin türünü içermiyor.

-veya-

Özelliğin set erişimcisi bulunamadı.

-veya-

value türüne PropertyTypedönüştürülemez.

Nesne hedef türüyle eşleşmiyor veya bir özellik bir örnek özelliğidir, ancak obj şeklindedir null.

Not: Windows Mağazası uygulamaları için .NET'te veya Taşınabilir Sınıf Kitaplığı'nda bunun yerine yakalayın Exception .

içindeki index parametre sayısı, dizine alınan özelliğin aldığı parametre sayısıyla eşleşmiyor.

Bir sınıfın içinde özel veya korumalı bir yönteme erişmeye yönelik yasadışı bir girişim vardı.

Not: Windows Mağazası uygulamaları için .NET'te veya Taşınabilir Sınıf Kitaplığı'nda bunun yerine temel sınıf özel durumunu MemberAccessExceptionyakalayın.

Özellik değeri ayarlanırken bir hata oluştu. Örneğin, dizinli özellik için belirtilen dizin değeri aralık dışındadır. InnerException özelliği hatanın nedenini gösterir.

Örnekler

Aşağıdaki örnek adlı read-write özelliğine sahip adlı TestClassCaptionbir sınıfı tanımlar. Özelliğin varsayılan değerini Caption görüntüler, özellik değerini değiştirmek için yöntemini çağırır SetValue ve sonucu görüntüler.

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.

Caption özelliği bir parametre dizisi olmadığından bağımsız değişkeninin index olduğunu nullunutmayın.

Aşağıdaki örnek üç özelliğe sahip adlı Example bir sınıf bildirir: bir static özellik (Shared Visual Basic'te), örnek özelliği ve dizine alınan örnek özelliği. Örnek, özelliklerin SetValue varsayılan değerlerini değiştirmek için yöntemini kullanır ve özgün ve son değerleri görüntüler.

Yansımalı bir dizinlenmiş örnek özelliğini aramak için kullanılan ad, dile ve özelliğe uygulanan özniteliklere bağlı olarak farklıdır.

  • Visual Basic'te özellik adı her zaman yansımalı özelliği aramak için kullanılır. özelliğini varsayılan dizinlenmiş özellik yapmak için anahtar sözcüğünü kullanabilirsiniz Default . Bu durumda, bu örnekte olduğu gibi özelliğe erişirken adı atlayabilirsiniz. Özellik adını da kullanabilirsiniz.

  • C# dilinde dizine alınan örnek özelliği, dizin oluşturucu olarak adlandırılan varsayılan bir özelliktir ve koddaki özelliğe erişirken ad hiçbir zaman kullanılmaz. Varsayılan olarak, özelliğin adı şeklindedir Itemve yansımalı özelliği ararken bu adı kullanmanız gerekir. Dizin oluşturucuya IndexerNameAttribute farklı bir ad vermek için özniteliğini kullanabilirsiniz. Bu örnekte adı şeklindedir IndexedInstanceProperty.

  • C++'da tanımlayıcı, default dizine alınan bir özelliği varsayılan dizinlenmiş özellik (sınıf dizin oluşturucu) yapmak için kullanılabilir. Bu durumda, özelliğin adı varsayılan olarak şeklindedir Itemve bu örnekte olduğu gibi yansımalı özelliği ararken bu adı kullanmanız gerekir. Sınıf dizin oluşturucusunun yansımasında farklı bir ad vermesi için özniteliğini kullanabilirsiniz IndexerNameAttribute , ancak koddaki özelliğe erişmek için bu adı kullanamazsınız. Sınıf dizin oluşturucu olmayan dizinli özelliğe hem kodda hem de yansımada adı kullanılarak erişilir.

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'

Açıklamalar

Bu PropertyInfo nesne bir değer türüyse ve value ise null, özelliği bu tür için varsayılan değere ayarlanır.

Bir özelliğin dizine eklenmiş olup olmadığını belirlemek için yöntemini kullanın GetIndexParameters . Sonuçta elde edilen dizide 0 (sıfır) öğe varsa, özellik dizine alınmaz.

Bu, soyut SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo) yöntemin çalışma zamanı uygulamasını çağıranBindingFlags.Default, parametresinull, için BindingFlags ve nullCultureInfoiçin Binderöğesini belirten bir kolaylık yöntemidir.

yöntemini kullanmak SetValue için önce sınıfını temsil eden bir Type nesne alın. içinden Typeöğesini alın PropertyInfo. içinden PropertyInfoyöntemini kullanın SetValue .

Not

.NET Framework 2.0'dan başlayarak, çağıranın ReflectionPermission bayrağı verilmişse ve ortak olmayan üyelerin izin kümesi çağıranın izin kümesiyle veya bunun bir alt kümesiyle ReflectionPermissionFlag.RestrictedMemberAccess kısıtlanmışsa, bu yöntem ortak olmayan üyelere erişmek için kullanılabilir. (Bkz. Yansıma için GüvenlikLe İlgili Dikkat Edilmesi Gerekenler.) Bu işlevi kullanmak için uygulamanızın 3.5 veya sonraki .NET Framework hedeflemesi gerekir.

Şunlara uygulanır

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

Kaynak:
PropertyInfo.cs
Kaynak:
PropertyInfo.cs
Kaynak:
PropertyInfo.cs

Türetilmiş bir sınıfta geçersiz kılındığında, belirtilen bağlama, dizin ve kültüre özgü bilgilere sahip belirtilen nesnenin özellik değerini ayarlar.

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)

Parametreler

obj
Object

Özellik değeri ayarlanacak nesne.

value
Object

Yeni özellik değeri.

invokeAttr
BindingFlags

Çağırma özniteliğini belirten aşağıdaki numaralandırma üyelerinin bit düzeyinde birleşimi: InvokeMethod, CreateInstance, Static, GetField, SetField, , GetPropertyveya SetProperty. Uygun bir çağırma özniteliği belirtmeniz gerekir. Örneğin, statik bir üyeyi çağırmak için bayrağını Static ayarlayın.

binder
Binder

Bağlamayı, bağımsız değişken türlerini zorlamayı, üyeleri çağırmayı ve nesneleri yansıma aracılığıyla almayı MemberInfo sağlayan bir nesne. ise bindernull, varsayılan bağlayıcı kullanılır.

index
Object[]

Dizine alınan özellikler için isteğe bağlı dizin değerleri. Bu değer dizine alınamayan özellikler için olmalıdır null .

culture
CultureInfo

Kaynağın yerelleştirileceği kültür. Kaynak bu kültür için yerelleştirilmemişse, Parent eşleşme aramasında özellik ardışık olarak çağrılır. Bu değer ise null, kültüre özgü bilgiler özelliğinden CurrentUICulture alınır.

Uygulamalar

Özel durumlar

Dizi index , gereken bağımsız değişkenlerin türünü içermiyor.

-veya-

Özelliğin set erişimcisi bulunamadı.

-veya-

value türüne PropertyTypedönüştürülemez.

Nesne hedef türüyle eşleşmiyor veya bir özellik bir örnek özelliğidir, ancak obj şeklindedir null.

içindeki index parametre sayısı, dizine alınan özelliğin aldığı parametre sayısıyla eşleşmiyor.

Bir sınıfın içinde özel veya korumalı bir yönteme erişmeye yönelik yasadışı bir girişim vardı.

Özellik değeri ayarlanırken bir hata oluştu. Örneğin, dizinli özellik için belirtilen dizin değeri aralık dışındadır. InnerException özelliği hatanın nedenini gösterir.

Açıklamalar

Bu PropertyInfo nesne bir değer türüyse ve value ise null, özelliği bu tür için varsayılan değere ayarlanır.

Bir özelliğin dizine eklenmiş olup olmadığını belirlemek için yöntemini kullanın GetIndexParameters . Sonuçta elde edilen dizide 0 (sıfır) öğe varsa, özellik dizine alınmaz.

Tam olarak güvenilen kod için erişim kısıtlamaları yoksayılır. Yani özel oluşturucular, yöntemler, alanlar ve özellikler koda tam olarak güvenildiğinde Yansıma aracılığıyla erişilebilir ve çağrılabilir.

yöntemini kullanmak SetValue için önce sınıfını Typealın. içinden Typeöğesini alın PropertyInfo. içinden PropertyInfoyöntemini kullanın SetValue .

Not

.NET Framework 2.0'dan başlayarak, çağıranın ReflectionPermission bayrağı verilmişse ve ortak olmayan üyelerin izin kümesi çağıranın izin kümesiyle veya bunun bir alt kümesiyle ReflectionPermissionFlag.RestrictedMemberAccess kısıtlanmışsa, bu yöntem ortak olmayan üyelere erişmek için kullanılabilir. (Bkz. Yansıma için GüvenlikLe İlgili Dikkat Edilmesi Gerekenler.) Bu işlevi kullanmak için uygulamanızın 3.5 veya sonraki .NET Framework hedeflemesi gerekir.

Şunlara uygulanır