2012-01-17 60 views
0

我正在使用PETAPOCO製作一個通用對象列表,然後綁定到一個gridview。但是,由於列名不是有效的屬性名稱,所以它們通過T4代碼進行更改。我想遍歷gridview列並更改標題文本以顯示實際的列名稱。當我只有屬性名稱的字符串表示形式時,獲取POCO屬性的列屬性的最佳方法是什麼?這是從我的poco獲取真實列名的最佳方式是什麼?

例如,我有:

[ExplicitColumns] 
public partial class SomeTable : DB.Record<SomeTable> 
{ 

    [Column("5F")] 
    public int _5F 
    { 
     get {return __5F;} 
     set {__5F = value; 
      MarkColumnModified("5F");} 
    } 
    int __5F; 
} 

我想常規,如:

public string GetRealColumn(string ObjectName, sting PropertyName) 

這樣:GetRealColumn( 「SomeTable」, 「_5F」)返回 「5F」

有什麼建議嗎?

回答

0

你總是可以使用反射來相處的線被應用到該屬性的屬性,事:

public string GetRealColumn(string objectName, string propertyName) 
{ 
    //this can throw if invalid type names are used, or return null of there is no such type 
    Type t = Type.GetType(objectName); 
    //this will only find public instance properties, or return null if no such property is found 
    PropertyInfo pi = t.GetProperty(propertyName); 
    //this returns an array of the applied attributes (will be 0-length if no attributes are applied 
    object[] attributes = pi.GetCustomAttributes(typeof(ColumnAttribute)); 
    ColumnAttribute ca = (ColumnAttribute) attributes[0]; 
    return ca.Name; 
} 

爲了簡潔和清晰起見,我已經被遺漏的錯誤檢查,你應該添加一些以確保它在運行時不會失敗。這不是生產質量代碼。

此外反射速度通常會變慢,因此最好緩存結果。

+0

感謝。這就是我在我的代碼中所做的事情,但我想確保我不會錯過一些晦澀的方式,通過petapoco庫中一些我不知道的奇怪調用來獲取列。 – Steve 2012-01-18 13:47:58

+0

尚未使用PetaPoco,但從我所看到的源代碼中,似乎並沒有將其作爲內置功能。 – SWeko 2012-01-18 14:02:12

0

好吧,如果你打算做這個有很多,你可以做這樣的事情:

  1. 創建的基本接口所有PetaPoco類都繼承。
  2. 從繼承接口的「SomeTable」創建一個部分類。
  3. 定義允許您提供列名稱的​​靜態擴展。這應該在設置時返回定義的「ColumnAttribute」名稱,否則返回在類上定義的名稱。

namespace Example { 
    //Used to make sure the extension helper shows when we want it to. This might be a repository....?? 
     public interface IBaseTable { } 

     //Partial class must exist in the same namespace 
     public partial class SomeTable : IBaseTable { } 
    } 

public static class PetaPocoExtensions { 
    public static string ColumnDisplayName(this IBaseTable table, string columnName) { 
     var attr = table.GetType().GetProperty(columnName).GetCustomAttributes(typeof(ColumnAttribute), true); 
     return (attr != null && attr.Count() > 0) ? ((ColumnAttribute)attr[0]).Name : columnName; 
    } 
} 

現在,你怎麼稱呼它,像這樣:

SomeTable table = new SomeTable(); 
    var columnName = table.ColumnDisplayName("_5F"); 
相關問題