3

我们将 Glass Mapper 与 Sitecore 一起使用,通过我们的模型,我们可以获得 sitecore 字段的值。但我想通过使用模型轻松获取站点核心字段(站点核心字段类型),而不将任何字符串(使用时GetProperty(),您需要属性名称字符串)硬编码到方法中。

所以我写了这个东西来实现这一点,但是我对使用它时需要传入 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

I don't understand why my question got down-voted. So you think it's perfect code already?

With help of another senior developer, I improved it today so it doesn't need 2 types any more and much clearer on usage syntax:

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

and I can just call it by doing this:

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

Hope it helps anyone who is using Glass Mapper with Sitecore and want to get current sitecore field from model property.

于 2014-09-03T10:14:59.433 回答