zha*_*nke 3 c# sitecore glass-mapper
我们将 Glass Mapper 与 Sitecore 结合使用,通过我们的模型,我们可以获得 sitecore 字段的值。但我想通过使用模型轻松获取 sitecore 字段(sitecore 字段类型),而不将任何字符串(使用时GetProperty(),您需要属性名称 string )硬编码到方法中。
所以我写了这个东西来实现这个目的,但是我对使用它时需要传递两种类型不满意,因为当你有一个很长的模型标识符时它看起来很糟糕。
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;
}
Run Code Online (Sandbox Code Playgroud)
最理想的方式就是能够像这样得到它Model.SomeProperty.SitecoreField()。但是我不知道如何从那里进行反射。因为这可以是任何类型的扩展。
谢谢!
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我放置inherit=true了GetCustomAttributes方法调用。
否则继承的属性将被忽略。