2014-02-06 49 views
0

使用反射,我得到了一組PropertyInfo屬性:反射訪問屬性,如果它有一個名爲「名稱」

var infos = typeof(T).GetProperties(.....) 

我對象(簡體)

Customer 
    Dog (class with field 'Name') 
    Cow (class with field 'Name') 
    FName (string) 

當我環路儘管相關信息,我的控制檯寫下屬性的值。如果該屬性是一個類(狗,牛等),並且該類具有「名稱」屬性,那麼我需要編寫「名稱」值。

基本上我怎麼確定MemeberInfo是一類,具有財產所謂的「名」,並把它寫出來?

回答

1

@莫霍是正確的,但它沒有解釋如何寫出我認爲你想要的實際名稱。

這將做到這一點,假設你的Customer對象是一個名爲obj變量:

 foreach (var pi in typeof(T).GetProperties()) 
     { 
      var propertyValue = pi.GetValue(obj); // This is the Dog or Cow object 
      var pt = pi.PropertyType; 

      var nameProperty = pt.GetProperty("Name"); 
      if (pt.IsClass && nameProperty != null) 
      { 
       var name = nameProperty.GetValue(propertyValue); // This pulls the name off of the Dog or Cow 
       Console.WriteLine(name); 
      } 
     } 
1
foreach(var pi in typeof(startingType).GetProperties()) 
{ 
    var pt = pi.PropertyType; 

    if(pt.IsClass && null != pt.GetProperty("Name")) 
    { 
     Console.WriteLine(pt.Name + " (class with field 'Name')"); 
    } 
} 
+0

該好好嘗試一下講解如何寫出來... –

+0

這是錯誤的,它將輸出'命名'pt'對象的屬性不是屬性的值。 –

+0

啊,我誤解了,他想要物業的實際價值 – Moho

相關問題