1

私はPETAPOCOを使用して、グリッドビューにバインドされるジェネリックオブジェクトのリストを作成しています。ただし、列名は有効なプロパティ名ではないため、T4コードによって変更されます。グリッドビューの列をループして、実際の列名を表示するようにヘッダーテキストを変更したいと思います。プロパティ名の文字列表現がある場合に、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 に答える