使用具有混合属性类型的成员表达式的 C# params 方法

本文关键字:成员 表达式 params 方法 类型 混合 属性 | 更新日期: 2023-09-27 18:35:37

我编写了一个接受成员表达式的params方法,并观察到编译器不会接受表达式中的混合属性类型。这是我的代码

public class MyClass<TEntity>
{
  public MyMethod<TEntity> Column<TProp>(params Expression<Func<TEntity, TProp>>[] expressions)
  { ... }
}
public class Customer
{
  property int Id {get; set;}
  property string Name {get; set;}
  property int Age {get; set;}
}
var mc = new MyClass<Customer>();
mc.MyMethod(c=>c.Id, c=>c.Age); // Works fine, using 2 int types
mc.MyMethod(c=>c.Id, c=>c.Name); // Results into a compile error, using int and string type mixed

我知道,编译器从关键字参数创建一个数组,但该数组的类型是Expression<Func<TEntity,TProp>>
这可以解决吗,而无需用大量 MyMethods 重载和增加参数列表替换 params 关键字?

使用具有混合属性类型的成员表达式的 C# params 方法

  1. 将参数类型更改为 Expression<Func<TEntity, object>>

  2. 添加以下代码以获取实际成员:

    public void MyMethod(params Expression<Func<TEntity, object>>[] expressions)
    {
        var members = from expression in expressions
                        let cast = expression.Body as UnaryExpression
                        let member = (expression.Body as MemberExpression)
                                    ?? cast.Operand as MemberExpression
                        where member != null
                        select member.Member;
    }
    

由于您似乎没有一个TProp,您也可以将其替换为object并使其成为非通用:

public MyMethod<TEntity> Column(params Expression<Func<TEntity, object>>[] expressions)