【问题标题】:Func<T,bool> Extend the conditionFunc<T,bool> 扩展条件
【发布时间】:2020-09-28 07:46:10
【问题描述】:

我有一个接受Func&lt;T,bool&gt; 条件作为参数的方法,我想将条件扩展为:

public T SomeClass.GETConditionalValue(x=>x.Id==id).ToList();

现在这个SomeClass.GETConditionalValue 需要一个参数Func&lt;T,bool&gt; 条件 我想修改它而不打扰SomeClass.GETConditionalValue

类似这样的:

public T SomeClass.GETConditionalValue(ApplyFilter(x=>x.Id==id)).ToList();

在哪里

public Func<T,bool>ApplyFilter<T>(Func<T,bool>condition) where T: GenericCLass
{

   return condition (+ some new condition in & or || block) 
}

**UPDATE :- ** 不能在这里使用委托,抛出无法将 lemda 表达式转换为 bool 类型,因为它不是委托类型

   public IEnumerable<T> GetEntities<T>(Func<T, bool> condition) where T : ITableEntity, new()
        {
            if (applicationFilter == null)
                return tableContext.CreateQuery<T>().Where(condition).ToList();
            return tableContext.CreateQuery<T>().Where(applicationFilter).Where(condition).ToList();
        }
 

我的电话是

 var mappedApplications = userToMdouleRepo.GetEntities<UserMappingToModules>(x => x.UserEmail == email)

这里我想改一下

 var mappedApplications = userToMdouleRepo.GetEntities<UserMappingToModules>(ApplyAdditionalFilter(x => x.UserEmail == email)).ToList()

【问题讨论】:

  • 换句话说,ApplyFilter 应该返回一个委托?
  • 是的,问题是您可以像 (condition && x=>x.Name=="Hi") 一样扩展 func 条件
  • @Fildor 我不能使用代理
  • 正在使用委托:Func<T,TResult> Delegate
  • 我的意思是我继续扩展它的抛出错误的条件

标签: c# asp.net .net .net-core


【解决方案1】:

你可以这样做:

public Func<T, bool> ApplyFilter<T>(Func<T, bool> condition) where T: GenericClass
{
    return t => condition(t) (+ some new condition in & or || block) 
}

例如:

public class GenericClass
{
    public string Name { get; }
}

public Func<T, bool> ApplyFilter<T>(Func<T, bool> condition) where T: GenericClass
{
    return t => condition(t) && t.Name == "SomeName";
}

【讨论】:

  • 没用 mate 无法将 lemda 表达式转换为 bool 类型,因为它不是 deligate 类型
  • @RAHULSR 你能发布你的 lambda 吗?这绝对应该编译:dotnetfiddle.net/VSrSPh
  • 请看一下
  • @RAHULSR 我的意思是你的ApplyFilter 实现,即导致编译器错误的地方。
  • @MongZhu 没有问题 T 是 ApplicationBaseEntity 继承了 ITableEntity 所以,而且我的过滤方法也在使用 ApplicationBaseEntity
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多