How to convert Func to Predicate?

前端 未结 4 2054
离开以前
离开以前 2020-12-01 12:34

Yes I\'ve seen this but I couldn\'t find the answer to my specific question.

Given a lambda testLambda that takes T and returns a boolean (I can mak

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 12:55

    Easy:

    Func func = x => x.Length > 5;
    Predicate predicate = new Predicate(func);
    

    Basically you can create a new delegate instance with any compatible existing instance. This also supports variance (co- and contra-):

    Action actOnObject = x => Console.WriteLine(x);
    Action actOnString = new Action(actOnObject);
    
    Func returnsString = () => "hi";
    Func returnsObject = new Func(returnsString);
    
    
    

    If you want to make it generic:

    static Predicate ConvertToPredicate(Func func)
    {
        return new Predicate(func);
    }
    

    提交回复
    热议问题