开发者

Is there a cleaner way to check if an object is not false?

开发者 https://www.devze.com 2023-02-21 21:17 出处:网络
Is there a cleaner way to write this? if (!(obj is bool) || (bool)obj) In PHP or JS you could write if (obj !== false) // note the double == to indicate a type-c开发者_开发技巧heck

Is there a cleaner way to write this?

if (!(obj is bool) || (bool)obj)

In PHP or JS you could write

if (obj !== false) // note the double == to indicate a type-c开发者_开发技巧heck

It's just a little hard to read, and pretty syntactically ugly in C#.


To be absolutely clear, obj is an object.


if (!false.Equals(obj))  { ... }

Edit: Since I don't want @BoltClock to lose his eyesight, here's something that might be better:

if ((bool?)obj != false) { ... }

Edit 2: Don't try what I put above, because it won't work if obj is of a type other than bool? or bool.


Yes, there is. Change your code such that the type of obj is bool and not object.

Somewhere in your code you converted your bool into an object. Why did you that? Find that place and keep it as a bool.

This is C# and not PHP or JS. C# is strongly typed - use that fact!


try this, its easy to read and sometimes code needs to be ledgible..

if (obj.Equals(false))
0

精彩评论

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