开发者

Predicate<Bool>, pointless or useful?

开发者 https://www.devze.com 2022-12-19 05:39 出处:网络
I\'m trying to get my head around the Predicate<T> type and I can understand it when T is anything, except for bool.If you have Predicate<bool>, I don\'t see how that can be used.

I'm trying to get my head around the Predicate<T> type and I can understand it when T is anything, except for bool. If you have Predicate<bool>, I don't see how that can be used.

Can someone tell me if this is a silly thing to do or if it actually serves a purpose?

Predicate<T> already returns a bool, so then testing a condition on a bool seems a bit 开发者_开发百科pointless... or have I got it wrong?


Predicate means a function that takes a T (any type) and returns a bool.

Predicate<int> isEven = i => i % 2 == 0;

You're mostly right. For bool, there's not many uses that come to mind. I mean, there's only so much you can do with a bool.

Predicate<bool> isFalse = input => !input;
Predicate<bool> isTrue = input => input;

You might use it like this:

var listOfBools = new List<Bool>() { true, false, false, true, true };
var trues = listOfBools.FindAll(isTrue);
var falses = listOfBools.FindAll(isFalse);

It's certainly less useful, simply because there's only so many things you can do with a bool.


Well, just because you have a bool already doesn't mean that you want to return exactly that bool. For instance i can imagine the IsFalse predicate that returns true if the argument is false.

0

精彩评论

暂无评论...
验证码 换一张
取 消