Linq表达式索引器属性

Paw*_*anS 3 c# linq asp.net entity-framework linq-expressions

var param = Expression.Parameter(typeof(Employee), "t");    
MemberExpression member = Expression.Property(param, "EmployeeName");
var value = Convert.ChangeType(filterProperty.Value, member.Type);
ConstantExpression constant = Expression.Constant(value);
var body = Expression.Or(leftExpr, Expression.Equal(member, constant));
Run Code Online (Sandbox Code Playgroud)

我可以轻松获取正常属性的表达式,但是如何获取索引器属性的表达式?

Employee课堂上我有两个索引器.

    class Employee
    {
       public string EmployeeName {get;set;}

       public string this[EmployeeTypes empType]
       {
          get
           {
             return GetEmployee(empType);
           }
       }

       public string this[int empNum]
       {
          get
           {
             return GetEmployee(empNum);
           }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*zek 5

使用Item物业名称:

var param = Expression.Parameter(typeof(Employee), "t");
MemberExpression member = Expression.Property(param, "EmployeeName");
var body = Expression.Property(param, "Item", Expression.Constant(10));
var lambda = Expression.Lambda<Func<Employee, string>>(body, param);
var compiled = lambda.Compile();
Run Code Online (Sandbox Code Playgroud)

给你的是可以做的

Func<Employee, string> compiled = t => t[10];
Run Code Online (Sandbox Code Playgroud)

  • 这意味着您的"员工"课程看起来并不像您向我们展示的那样.我用你的示例`Employee`类对它进行了测试,结果正常. (2认同)
  • 这适用于大多数索引器,但不适用于所有索引器。索引器属性通常称为“Item”,但并非必须如此。例如,[“string”的索引器称为“Chars”](http://msdn.microsoft.com/en-us/library/system.string.chars.aspx)。 (2认同)