How do I safely cast a System.Object to a `bool` in C#?

前端 未结 10 1756
情话喂你
情话喂你 2021-01-30 19:41

I am extracting a bool value from a (non-generic, heterogeneous) collection.

The as operator may only be used with reference types, so it is no

10条回答
  •  别跟我提以往
    2021-01-30 20:22

    If the goal is to have true only if the raw object is boolean 'true' then one-liner (rawValue as bool?)?? false will do:

    object rawValue=null
    (rawValue as bool?)?? false
    false
    rawValue="some string"
    (rawValue as bool?)?? false
    false
    rawValue=true
    (rawValue as bool?)?? false
    true
    rawValue="true"
    (rawValue as bool?)?? false
    false
    rawValue=false
    (rawValue as bool?)?? false
    false
    rawValue=""
    (rawValue as bool?)?? false
    false
    rawValue=1
    (rawValue as bool?)?? false
    false
    rawValue=new Dictionary()
    (rawValue as bool?)?? false
    false`
    

提交回复
热议问题