2012-01-17 63 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"); 
相关问题