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

前端 未结 10 1608
情话喂你
情话喂你 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<string,string>()
    (rawValue as bool?)?? false
    false`
    
    0 讨论(0)
  • 2021-01-30 20:22

    You can also simply do, if it fits:

    if(rawValue is true)
    {
        //do stuff
    }
    
    0 讨论(0)
  • 2021-01-30 20:25

    You can cast it to a bool? with the as keyword and check the HasValue property.

    0 讨论(0)
  • 2021-01-30 20:25

    I used this check before doing something with object

    if(myCrazyObject.GetType().Equals(typeof(bool)))
    {
       //do smt with it
    }
    
    0 讨论(0)
提交回复
热议问题