我使用了一些强类型表达式,这些表达式被序列化以允许我的UI代码具有强类型排序和搜索表达式.这些是类型的Expression<Func<TModel,TProperty>>并且如此使用:SortOption.Field = (p => p.FirstName);.对于这个简单的案例,我已经完美地完成了这项工作.
我用来解析"FirstName"属性的代码实际上重用了我们使用的第三方产品中的一些现有功能,并且它工作得很好,直到我们开始使用深层嵌套的属性(SortOption.Field = (p => p.Address.State.Abbreviation);).此代码在支持深层嵌套属性的需求方面有一些非常不同的假设.
至于这段代码的作用,我并不是真的理解它而不是改变代码,我想我应该从头开始编写这个功能.但是,我不知道这样做的好方法.我怀疑我们可以做一些比做ToString()和执行字符串解析更好的事情.那么有什么好办法来处理琐碎和深层嵌套的案例呢?
要求:
p => p.FirstName我需要一串"FirstName".p => p.Address.State.Abbreviation我需要一串"Address.State.Abbreviation"虽然对我的问题的答案并不重要,但我怀疑我的序列化/反序列化代码对将来发现这个问题的其他人有用,所以它在下面.同样,这段代码对这个问题并不重要 - 我只是觉得它可能对某些人有所帮助.请注意,DynamicExpression.ParseLambda它来自动态LINQ的东西,Property.PropertyToString()这是这个问题的关键.
/// <summary>
/// This defines a framework to pass, across serialized tiers, sorting logic to be performed.
/// </summary>
/// <typeparam name="TModel">This is the object type that you are filtering.</typeparam>
/// <typeparam name="TProperty">This is the property on the object that you are filtering.</typeparam>
[Serializable]
public class SortOption<TModel, TProperty> : ISerializable where TModel : class
{
/// <summary>
/// Convenience constructor.
/// </summary>
/// <param name="property">The property to sort.</param>
/// <param name="isAscending">Indicates if the sorting should be ascending or descending</param>
/// <param name="priority">Indicates the sorting priority where 0 is a higher priority than 10.</param>
public SortOption(Expression<Func<TModel, TProperty>> property, bool isAscending = true, int priority = 0)
{
Property = property;
IsAscending = isAscending;
Priority = priority;
}
/// <summary>
/// Default Constructor.
/// </summary>
public SortOption()
: this(null)
{
}
/// <summary>
/// This is the field on the object to filter.
/// </summary>
public Expression<Func<TModel, TProperty>> Property { get; set; }
/// <summary>
/// This indicates if the sorting should be ascending or descending.
/// </summary>
public bool IsAscending { get; set; }
/// <summary>
/// This indicates the sorting priority where 0 is a higher priority than 10.
/// </summary>
public int Priority { get; set; }
#region Implementation of ISerializable
/// <summary>
/// This is the constructor called when deserializing a SortOption.
/// </summary>
protected SortOption(SerializationInfo info, StreamingContext context)
{
IsAscending = info.GetBoolean("IsAscending");
Priority = info.GetInt32("Priority");
// We just persisted this by the PropertyName. So let's rebuild the Lambda Expression from that.
Property = DynamicExpression.ParseLambda<TModel, TProperty>(info.GetString("Property"), default(TModel), default(TProperty));
}
/// <summary>
/// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param>
/// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Just stick the property name in there. We'll rebuild the expression based on that on the other end.
info.AddValue("Property", Property.PropertyToString());
info.AddValue("IsAscending", IsAscending);
info.AddValue("Priority", Priority);
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*Tao 92
这是诀窍:这种形式的任何表达......
obj => obj.A.B.C // etc.
Run Code Online (Sandbox Code Playgroud)
......实际上只是一堆嵌套MemberExpression对象.
首先你有:
MemberExpression: obj.A.B.C
Expression: obj.A.B // MemberExpression
Member: C
Run Code Online (Sandbox Code Playgroud)
评估Expression上面的MemberExpression为您提供:
MemberExpression: obj.A.B
Expression: obj.A // MemberExpression
Member: B
Run Code Online (Sandbox Code Playgroud)
最后,以上这(在"顶部"),你必须:
MemberExpression: obj.A
Expression: obj // note: not a MemberExpression
Member: A
Run Code Online (Sandbox Code Playgroud)
所以似乎很清楚,解决这个问题的方法是检查Expression一个MemberExpressionup 的属性,直到它不再是一个a MemberExpression.
更新:似乎你的问题有一个额外的旋转.可能你有一些看起来像Func<T, int>......的lambda
p => p.Age
Run Code Online (Sandbox Code Playgroud)
......但实际上是一个Func<T, object>; 在这种情况下,编译器会将上面的表达式转换为:
p => Convert(p.Age)
Run Code Online (Sandbox Code Playgroud)
实际上,调整此问题并不像看起来那么难.看看我的更新代码,找到一种方法来处理它.请注意,通过抽象代码来获取MemberExpression它自己的方法(TryFindMemberExpression),这种方法使GetFullPropertyName方法相当干净,并允许您将来添加额外的检查 - 如果您可能发现自己面临一个新的方案,你没有最初的原因 - 不必涉及过多的代码.
为了说明:这段代码对我有用.
// code adjusted to prevent horizontal overflow
static string GetFullPropertyName<T, TProperty>
(Expression<Func<T, TProperty>> exp)
{
MemberExpression memberExp;
if (!TryFindMemberExpression(exp.Body, out memberExp))
return string.Empty;
var memberNames = new Stack<string>();
do
{
memberNames.Push(memberExp.Member.Name);
}
while (TryFindMemberExpression(memberExp.Expression, out memberExp));
return string.Join(".", memberNames.ToArray());
}
// code adjusted to prevent horizontal overflow
private static bool TryFindMemberExpression
(Expression exp, out MemberExpression memberExp)
{
memberExp = exp as MemberExpression;
if (memberExp != null)
{
// heyo! that was easy enough
return true;
}
// if the compiler created an automatic conversion,
// it'll look something like...
// obj => Convert(obj.Property) [e.g., int -> object]
// OR:
// obj => ConvertChecked(obj.Property) [e.g., int -> long]
// ...which are the cases checked in IsConversion
if (IsConversion(exp) && exp is UnaryExpression)
{
memberExp = ((UnaryExpression)exp).Operand as MemberExpression;
if (memberExp != null)
{
return true;
}
}
return false;
}
private static bool IsConversion(Expression exp)
{
return (
exp.NodeType == ExpressionType.Convert ||
exp.NodeType == ExpressionType.ConvertChecked
);
}
Run Code Online (Sandbox Code Playgroud)
用法:
Expression<Func<Person, string>> simpleExp = p => p.FirstName;
Expression<Func<Person, string>> complexExp = p => p.Address.State.Abbreviation;
Expression<Func<Person, object>> ageExp = p => p.Age;
Console.WriteLine(GetFullPropertyName(simpleExp));
Console.WriteLine(GetFullPropertyName(complexExp));
Console.WriteLine(GetFullPropertyName(ageExp));
Run Code Online (Sandbox Code Playgroud)
输出:
FirstName
Address.State.Abbreviation
Age
Run Code Online (Sandbox Code Playgroud)
dri*_*iis 15
这是一个允许您获取字符串表示的方法,即使您有嵌套属性:
public static string GetPropertySymbol<T,TResult>(Expression<Func<T,TResult>> expression)
{
return String.Join(".",
GetMembersOnPath(expression.Body as MemberExpression)
.Select(m => m.Member.Name)
.Reverse());
}
private static IEnumerable<MemberExpression> GetMembersOnPath(MemberExpression expression)
{
while(expression != null)
{
yield return expression;
expression = expression.Expression as MemberExpression;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你仍然在.NET 3.5上,你需要ToArray()在调用之后粘贴Reverse(),因为在.NET 4中首先添加了String.Join一个重载IEnumerable.
对于来自p => p.FirstName的"FirstName"
Expression<Func<TModel, TProperty>> expression; //your given expression
string fieldName = ((MemberExpression)expression.Body).Member.Name; //watch out for runtime casting errors
Run Code Online (Sandbox Code Playgroud)
我建议您查看ASP.NET MVC 2代码(来自aspnet.codeplex.com),因为它有类似的Html助手API ... Html.TextBoxFor(p => p.FirstName)等
小智 5
另一种简单的方法是使用System.Web.Mvc.ExpressionHelper.GetExpressionText方法.在我的下一次打击中,我会写更详细的内容.看看http://carrarini.blogspot.com/.
| 归档时间: |
|
| 查看次数: |
26469 次 |
| 最近记录: |