1

我正在使用 PETAPOCO 制作一个通用对象列表,然后将这些对象绑定到一个网格视图。但是,由于列名不是有效的属性名,它们会被 T4 代码更改。我想遍历 gridview 列并更改标题文本以显示真实的列名。当我只有属性名称的字符串表示形式时,获取 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"

有什么建议么?

4

2 回答 2

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;
}

为了简洁明了,我省略了错误检查,您应该添加一些以确保它在运行时不会失败。这不是生产质量代码。

反射也往往很慢,所以最好缓存结果。

于 2012-01-17T08:59:28.030 回答
0

好吧,如果你要经常这样做,你可以这样做:

  1. 创建一个基础接口,您的所有 PetaPoco 类都将从该接口继承。
  2. 从继承接口的“SomeTable”创建一个部分类。
  3. 定义允许您提供列名的静态扩展。这应该在设置时返回定义的“ColumnAttribute”名称,否则返回类上定义的名称。

1 & 2

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 {    }
    }

3

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");
于 2012-02-21T20:36:24.367 回答