2012-06-23 62 views
0
public class Job 
{ 
    public string Name { get; set; } 
    public int Salary { get; set; } 
} 
public class Employee 
{ 
    public string Name { get; set; } 
    public Job Job { get; set; } 
} 

如果我想創建的成員訪問Employee.Name這個表達式樹是我做的:深度的成員訪問表達式樹> 1

 var param = Expression.Parameter(type, "x"); 
     var memberAccess = Expression.PropertyOrField(param, memberName); 
     return Expression.Lambda<Func<TModel, TMember>>(memberAccess, param); 

什麼是相當於這爲一個成員訪問Employee.Job.Salary?

+0

我試過使用我創建的memberAccess並在其上創建另一個memberAccess:Expression.PropertyOrField(baseMemberAccess,memberName),它沒有工作,它試圖找到基本成員內的memberName訪問Func <> –

回答

9

您需要:

var jobProperty = Expression.PropertyOrField(param, "Job"); 
var salaryProperty = Expression.PropertyOrField(jobProperty, "Salary"); 

基本上你從評估x.Job的結果採取Salary財產。

如果你需要這樣做以編程的方式,你需要這樣的:

Expression expression = Expression.Parameter(type, "x"); 
foreach (var property in properties.Split('.')) 
{ 
    expression = Expression.PropertyOrField(expression, property); 
} 
-1

的最好方法將創建擴展as here

public static class ExpressionExtensions 
{ 
    /// <summary> 
    ///  create expression by property name 
    /// </summary> 
    /// <typeparam name="TModel"></typeparam> 
    /// <param name="propertyName"> 
    ///  <example>Urer.Role.Name</example> 
    /// </param> 
    /// <returns></returns> 
    public static Expression<Func<TModel, dynamic>> CreateExpression<TModel>(this string propertyName) { 
     Type currentType = typeof (TModel); 
     ParameterExpression parameter = Expression.Parameter(currentType, "x"); 
     Expression expression = parameter; 

     int i = 0; 
     List<string> propertyChain = propertyName.Split('.').ToList(); 
     do { 
      System.Reflection.PropertyInfo propertyInfo = currentType.GetProperty(propertyChain[i]); 
      currentType = propertyInfo.PropertyType; 
      i++; 
      if (propertyChain.Count == i) 
      { 
       currentType = typeof (object); 
      } 
      expression = Expression.Convert(Expression.PropertyOrField(expression, propertyInfo.Name), currentType); 
     } while (propertyChain.Count > i); 

     return Expression.Lambda<Func<TModel, dynamic>>(expression, parameter); 
    } 
} 

您不能轉換()每次都要輸入typeof(object),因爲System.Object沒有屬性,你的類型有(例如Name或Salary)。