2011-08-02 16 views
19

Ben gibi basit bir sınıfı vardır: (int) veya (dize için) boş/boş boş değilse ben sınıfta özelliğinin her biri için nasıl kontrol ederimYansıma (?) - Bir sınıftaki her özellik/alan için boş veya boş olup olmadığını kontrol edin.

public class FilterParams 
{ 
    public string MeetingId { get; set; } 
    public int? ClientId { get; set; } 
    public string CustNum { get; set; } 
    public int AttendedAsFavor { get; set; } 
    public int Rating { get; set; } 
    public string Comments { get; set; } 
    public int Delete { get; set; } 
} 

, o zaman' Bu mülkün değerini List<string>'a dönüştürüp ekleme

Teşekkürler.

cevap

30
Sen için LINQ kullanabilirsiniz

Bunu yapın:

List<string> values 
    = typeof(FilterParams).GetProperties() 
          .Select(prop => prop.GetValue(yourObject, null)) 
          .Where(val => val != null) 
          .Select(val => val.ToString()) 
          .Where(str => str.Length > 0) 
          .ToList(); 
+0

Özellik "int" ve "0" değeri ise, prop.GetValue 'null' döndürüyor mu? – dtb

+0

@dtb, nope, bu durumda '0' döndürecekti. –

+0

@Frederic: 0'ları dahil etmek mi yoksa filtrelemek mi istiyorsunuz? –

5

Değil en güzel yaklaşım ama kabaca: bir örnek Burada

Type type = typeof(FilterParams); 


foreach(PropertyInfo pi in type.GetProperties()) 
{ 
    object value = pi.GetValue(obj, null); 

    if(value != null || !string.IsNullOrEmpty(value.ToString())) 
    // do something 
} 
0

oluyor: obj varsayarsak

sınıfın örneğidir

foreach (PropertyInfo item in typeof(FilterParams).GetProperties()) { 
    if (item != null && !String.IsNullOrEmpty(item.ToString()) { 
     //add to list, etc 
    } 
} 
+0

Haklısınız, snippet'i düzelttim. –

1
PropertyInfo[] properties = typeof(FilterParams).GetProperties(); 
foreach(PropertyInfo property in properties) 
{ 
    object value = property.GetValue(SomeFilterParamsInstance, null); 
    // preform checks on value and etc. here.. 
} 
0

Gerçekten bir yansımama mı ihtiyacınız var? bool IsNull gibi bir özelliği uygulamak sizin için bir durum mu? INullableEntity gibi bir arayüz içinde kapsülleyebilir ve böyle bir işleve ihtiyaç duyan her sınıfta uygulayabilirsiniz, belki de çok fazla sınıf varsa, yansıma ile uğraşmanız gerekir.

public class FilterParams 
{ 
    // ... 

    public IEnumerable<string> GetValues() 
    { 
     if (MeetingId != null) yield return MeetingId; 
     if (ClientId.HasValue) yield return ClientId.Value.ToString(); 
     // ... 
     if (Rating != 0)  yield return Rating.ToString(); 
     // ... 
    } 
} 

Kullanımı:

2

Böyle sınıflar ve çok fazla değil çok sayıda mülk yoksa

, basit çözüm, her özelliği denetler ve dönüştüren bir iterator block yazmak için muhtemelen
FilterParams filterParams = ... 

List<string> values = filterParams.GetValues().ToList(); 
+0

Harika bir fikir! Teşekkürler. – Saxman

İlgili konular