Convert.ToBoolean fails with “0” value

后端 未结 8 2242
清歌不尽
清歌不尽 2020-12-14 16:37

I\'m trying to convert the value \"0\" ( System.String ) to its Boolean representation, like:

var myValue = Convert.To         


        
8条回答
  •  一向
    一向 (楼主)
    2020-12-14 17:29

    Since it's really a matter of still doing those conversions and such, how about an extension method?

    public static class Extensions {
        public static bool ToBool(this string s) {
            return s == "0" ? false : true;
        }
    }
    

    and so then you would use it like this:

    "0".ToBool();
    

    and now you could easily extend this method to handle even more cases if you wanted.

提交回复
热议问题