SORU
10 ŞUBAT 2009, Salı


Nasıl bir sınıfın tüm özelliklerini döngü?

Bir Dersim var.

Public Class Foo
    Private _Name As String
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _Age As String
    Public Property Age() As String
        Get
            Return _Age
        End Get
        Set(ByVal value As String)
            _Age = value
        End Set
    End Property

    Private _ContactNumber As String
    Public Property ContactNumber() As String
        Get
            Return _ContactNumber
        End Get
        Set(ByVal value As String)
            _ContactNumber = value
        End Set
    End Property


End Class

Üzerinden sınıf yukarıda özellikleri döngü istiyorum. örneğin;

Public Sub DisplayAll(ByVal Someobject As Foo)
    For Each _Property As something In Someobject.Properties
        Console.WriteLine(_Property.Name & "=" & _Property.value)
    Next
End Sub

CEVAP
10 ŞUBAT 2009, Salı


Yansıma Kullanın:

Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: "   property.Name   ", Value: "   property.GetValue(obj, null));
}

Edit: değeri type.GetProperties(): bir BindingFlags belirtebilirsiniz

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);

Ortak örnek özellikleri (statik özellikleri, korumalı özellikleri, vb hariç) iade edilen özellikleri sınırlar.

type.InvokeMember() bir özelliğin değerini almak için çağırırken kullandığınız BindingFlags.GetProperty, belirtmenize gerek yok.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • EEVblog2

    EEVblog2

    2 HAZİRAN 2014
  • khloe brooks

    khloe brooks

    25 Temmuz 2011
  • lilstevie89

    lilstevie89

    25 Mart 2011