2017-05-11 84 views
-1

我有簡單的類與方法ToHtmlString(),我想枚舉此對象(引用)的所有私有和實例屬性。爲什麼我不能拿這個價值。我看到我需要傳遞對象到GetValue方法,以便運行時知道哪個參考反射將獲得哪個值,但是看起來像我不能這樣做?枚舉此實例的所有屬性時如何使用GetValue在C#中的類的實例方法中使用GetValue方法

public string ToHtmlString() 
    { 
     var source = this; 
     var html = new StringBuilder(); 

     foreach (var property in this.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)) 
     { 
      html.AppendLine(
       new GenericItemView(
        (property.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute)?.Description, 
        property.GetValue(source).ToString()); 
     } 

     return html.ToString(); 
    } 
+1

請同時用[mcve]編輯問題。如果我們能夠輕鬆地重現問題,問題會更好。另外,說明問題 - 「爲什麼我不能接受這個價值」並沒有告訴我們任何關於你提供的代碼出了什麼問題的事情。 –

回答

1

它看起來像你缺少一個右 「)」 和的ToString()

html.AppendLine(新GenericItemView((property.GetCustomAttribute(typeof運算(DescriptionAttribute))作爲DescriptionAttribute)? Description,property.GetValue(source).ToString())。ToString());

+0

是的,我更可能忘記將'GenericItemView'對象轉換爲字符串。傻我。 – kuskmen

相關問題