Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将And语句添加到表达式_C#_Lambda - Fatal编程技术网

C# 将And语句添加到表达式

C# 将And语句添加到表达式,c#,lambda,C#,Lambda,我有这个功能: public List<T> Find(Expression<Func<T, bool>> query) { } Find(x => x.Id == 4); 差不多 Find(x => x.Id == 4 && x.Secured == false); 必须打开并重新生成表达式,如下所示: public List<T> Find<T>(Expression<Func<T,

我有这个功能:

public  List<T> Find(Expression<Func<T, bool>> query)
{
}

Find(x => x.Id == 4);
差不多

Find(x => x.Id == 4 && x.Secured == false);

必须打开并重新生成表达式,如下所示:

public List<T> Find<T>(Expression<Func<T, bool>> query)
{
    ParameterExpression parameter = query.Parameters[0];
    Expression body = query.Body;

    MemberExpression property = Expression.Property(parameter, "Secured");

    body = Expression.AndAlso(body, Expression.Not(property));

    Expression<Func<T, bool>> query2 = Expression.Lambda<Func<T, bool>>(body, parameter);

    // Now you can use query2

    return null;
}

我使用context.Set作为示例,这与使用Entity Framework时的操作非常相似,但通常几乎所有IQuerable/IEnumerable都将两个视为一个。如果使用&&condition,您的问题是希望在泛型方法中访问T的一个成员。此时T可以是任何值,因此编译器将不允许您访问受保护的,因为T可能没有受保护的成员

public  List<T> Find(Expression<Func<T, bool>> query) where T : ISecured
您可以将T强制转换为动态,但这只会将编译时错误更改为运行时错误,而且这非常可怕

最好的方法是确保T实现一些已知的接口,该接口有一个安全的成员

public  List<T> Find(Expression<Func<T, bool>> query) where T : ISecured

where not,可以有多个。Statement.Wherequery.Wherex=>!x、 安全的;或者像xanatos建议的那样使用表达式树:不过这也会将问题转移到运行时。
public  List<T> Find(Expression<Func<T, bool>> query) where T : ISecured