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

前端 未结 10 1770
情话喂你
情话喂你 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:02

    You haven't defined what you want to have happen if rawValue is not convertible to bool. Common choices are to return false, null, or throw an exception. There's also the possibility of the string representation of rawValue to be convertible to a bool, such as Yes/No, True/False, 1/0, etc.

    I would use bool.TryParse to do the conversion. This will succeed if rawValue is a bool or its string value is "True" or "False".

    bool result;
    if (!bool.TryParse(rawValue as string, out result))
    {
        // you need to decide what to do in this case
    }
    

提交回复
热议问题