使用谓词替换c#中的"if"的示例?

Ben*_*nny 2 c# predicate

我读到'if'关键字是邪恶的,最好使用谓词替换if.然后我用Google搜索,但仍然没有得到它.

任何人都可以善待提供一个例子吗?

Vin*_*vic 9

不管他们说什么,如果不是邪恶的话.可能存在一种特定情况,其中谓词是比if(或一组ifs)更好的选择.

例如,

 foreach (Foo f in fooList) {
     if (f.Equals(fooTarget)) {
        return f;
     }
 }
Run Code Online (Sandbox Code Playgroud)

与(.NET 2.0)

 fooList.Find(delegate (Foo f) { return f.Equals(fooTarget); });
Run Code Online (Sandbox Code Playgroud)

或(稍后)

 fooList.Find(f => f.Equals(fooTarget));
Run Code Online (Sandbox Code Playgroud)