3

Sitecore で Glass Mapper を使用しています。モデルを使用して、sitecore フィールドの値を取得できます。しかし、メソッドに文字列をハードコーディングせずにモデルを使用して、サイトコア フィールド (サイトコア フィールド タイプ) を簡単に取得したい (を使用GetProperty()する場合は、プロパティ名 string が必要です)。

だから私はこれを達成するためにこれを書きましたが、長いモデル識別子があるとひどく見えるので、それを使用するときに2つのタイプを渡す必要があることに満足していません.

   public static string SitecoreFieldName<T, TU>(Expression<Func<TU>> expr)
    {
         var body = ((MemberExpression)expr.Body);
         var attribute = (typeof(T).GetProperty(body.Member.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false)[0]) as SitecoreFieldAttribute;
         return attribute.FieldName;
    }

このように入手できるのが最も理想的な方法ですModel.SomeProperty.SitecoreField()。しかし、そこからリフェクションを行う方法がわかりません。それはあらゆるタイプの拡張になる可能性があるためです。

ありがとう!

4

2 に答える 2

5
public static string SitecoreFieldName<TModel>(Expression<Func<TModel, object>> field)
{
    var body = field.Body as MemberExpression;

    if (body == null)
    {
        return null;
    }

    var attribute = typeof(TModel).GetProperty(body.Member.Name)
        .GetCustomAttributes(typeof(SitecoreFieldAttribute), true)
        .FirstOrDefault() as SitecoreFieldAttribute;

    return attribute != null
        ? attribute.FieldName
        : null;
}

メソッド呼び出しをinherit=true行ったことに注意してください。 それ以外の場合、継承された属性は無視されます。GetCustomAttributes

于 2014-09-03T10:22:03.110 に答える
1

私の質問が反対票を投じられた理由がわかりません。すでに完璧なコードだと思いますか?

別の上級開発者の助けを借りて、私は今日それを改善したので、2 つの型が不要になり、使用構文がより明確になりました。

public static Field GetSitecoreField<T>(T model, Expression<Func<T, object>> expression) where T : ModelBase
    {
        var body = ((MemberExpression)expression.Body);
        var attributes = typeof(T).GetProperty(body.Member.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false);
        if (attributes.Any())
        {
            var attribute = attributes[0] as SitecoreFieldAttribute;
            if (attribute != null)
            {
                return model.Item.Fields[attribute.FieldName];
            }
        }
        return null;
    }

そして、私はこれを行うことでそれを呼び出すことができます:

GetSitecoreField(Container.Model<SomeModel>(), x => x.anyField)

Sitecore で Glass Mapper を使用していて、モデル プロパティから現在の sitecore フィールドを取得したい人に役立つことを願っています。

于 2014-09-03T10:14:59.433 に答える