2014-11-05 41 views
0

我正在編寫一些代碼,它將發送電子郵件,其中包含某個類的屬性內部的詳細信息。更改客戶端輸出的屬性名稱

而不是硬與性能的編碼行,我認爲這是最好的通過reflection

var builder = new StringBuilder(); 

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

foreach (PropertyInfo property in properties) 
{ 
    if (property.GetValue(obj, null) != null) 
    { 
     builder.AppendLine("<tr>"); 
     builder.AppendLine("<td>"); 

     builder.AppendLine("<b> " + property.Name + " </b>"); 

     builder.AppendLine("</td>"); 
     builder.AppendLine("<td>"); 

     builder.AppendLine(property.GetValue(obj, null).ToString()); 

     builder.AppendLine("</td>"); 
     builder.AppendLine("</tr>"); 
    } 
} 

這也有助於省去了尚未設置的所有屬性這又有助於減少這樣做碼。

然而property.Name相當正確地以目前的形式

public string PropertyA { get; set; } 

輸出屬性的名稱,以便在電子郵件看起來像

PropertyA : 123 

這does not看起來友好的用戶。那麼有沒有辦法改變屬性名稱來顯示不同的東西?

我已經試過

[DisplayName("Property A")] 
public string PropertyA { get; set; } 

應該看起來像電子郵件:

Property A : 123 

但沒有佔上風....是那裏有什麼幫助邏輯的道路上我要走了?

感謝

回答

2

您需要find the attribute and extract the Name value

var displayNameAttribute = property.GetCustomAttributes 
            (typeof(DisplayNameAttribute), false) 
            .FirstOrDefault() as DisplayNameAttribute; 

string displayName = displayNameAttribute != null 
         ? displayNameAttribute.DisplayName 
         : property.Name; 
+0

謝謝,因爲我的說的一樣第一個答案,它不屬於'attribute.Name'它的'attribute.DisplayName'對我來說很好...... – user3428422 2014-11-05 15:50:21

+0

謝謝,修正。 @ Selman22提出的'GetCustomAttribute <>()'擴展方法雖然有一些更好的語法。 – CodeCaster 2014-11-05 15:57:13

+0

以某種方式,我同意,但你做一個空的檢查:?但是,我並不那麼挑剔老實說,我可以將答案頒給@ Selman22。我通常只是首先給予答案,但你的答案基本相同。 – user3428422 2014-11-05 16:00:22

2

你需要讓你的財產DisplayNameAttribute,然後得到它的Name

var attribute = property.GetCustomAttribute<DisplayNameAttribute>(); 

if(attribute != null) 
{ 
    var displayName = attribute.Name; 
} 
+0

非常感謝!但對我來說,它的'attribute.Name'不是'attribute.DisplayName' – user3428422 2014-11-05 15:49:57