简体   繁体   中英

Casting System.Object to boolean

Under which circumstances would be (bool) mydata a valid cast when mydata type is System.Object ?

Ie, obviously it would be a valid cast if the actual or unrderlying type is a boolean.

But would it be also a valid cast if the underlying type is int or maybe string ? Eg,

int value=1;
object mydata=value;
if ((bool) value) { ... }

Actually I am wondering how explicit conversions work in C#. Is some kind of reflection used to check if any valid conversion exists even when dealing with object types?

An int is not a bool . Try it and find out what happens (InvalidCastException).

抛出InvalidlCastException

One should note that most of the primitive types explicitly implement IConvertible , so you can get the cast you want this way:

int    a = 37 ;
object b = a ;
bool   c = (b as IConvertible) != null && (b as IConvertible).ToBoolean(null);

In the case of an intbool conversion like this, the conversion is done in the usual C-like manner: zero is false and non-zero is true . Worth noting that this behaviour is at odds with formal logic wherein falsity is multi-valued, being all that is not true and truth uni-valued. But I digress.

As far as custom conversions go, whether implicit or explicit, all you're doing is providing custom methods that are recognized as operators by the compiler. The how of the conversion, of course, is up to you and your implementation. Here, the class Foo knows how to convert itself [explicitly] to an instance of class Bar :

class Foo
{
  public static explicit operator Bar(Foo x)
  {
    // your implementation here
    throw new NotImplementedException();
  }
}

And here, class Bar knows how to [explicitly] convert itself to an int and to [implicitly] convert itself to a Foo :

class Bar
{
    public static explicit operator int(Bar x)
    {
        // your implementation here
        throw new NotImplementedException();
    }
    public static implicit operator Foo(Bar x)
    {
        // your implementation here
        throw new NotImplementedException();
    }
}

When you start mixing stuff up, the compiler will figure out what conversion method(s) are applicable (or not) and resolve them. You'll either get a compile error about the conversion or the compile will have selected a conversion method to be invoked at runtime.

At runtime, of course, it is possible that an exception might be thrown in the course of the conversion.

Paraphrased from Eric Lippert's blog:

http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx

The C# cast operator is used for identity preserving conversions (eg interpret this reference to base class as a reference to derived class) and identity destroying conversions (eg convert this int to a double ). A single use of the cast operator is only allowed to invoke one of these.

Since you boxed an int , the only thing that the int may be unboxed to is int (this is an identity preserving case). Once it is unboxed to int , it may be converted (in the identity destroying case) to bool .

That is:

int iii = 123;
object ooo = iii;            // Box the int
bool bbb = (bool) iii;       // Perfectly legal
bool jjj = (bool) (int) ooo; // Perfectly legal
bool kkk = (bool) ooo;       // Invalid cast exception

First thing first: a cast of an object to bool is valid only when the object is a reference type wrapper for the bool or Nullable<bool> type:

bool val1 = true;
object mydata1=val1;
if ((bool) val1) { ... } // This is valid
bool? val2 = false;
object mydata2=val2;
if ((bool) val2) { ... } // This is valid too

When you cast an object to another type in C#, the runtime has enough information about the runtime type of the object being typecast to validate the operation, and throw an InvalidCastException when the cast is invalid.

In situations when the dynamic type of the object at runtime does not match the type to which you would like it to cast, you should use methods of the Convert class.

Probably your best course of action to reduce exceptions and make casting easy is to use the as operator and a nullable boolean bool? .

object test1 = 1;
object test2 = true;

var testBool1 = test1 as bool?;
var testBool2 = test2 as bool?;

if (testBool1.HasValue) 
{
  // test1 is a boolean
  bool mybool = testBool1.Value;
}

if (testBool2.HasValue)
{
  // test2 is a boolean
  bool mybool = testBool2.Value;
}

use this code for convert object to Boolean

 var t = propInfo.GetValue(item, null);
bool state = Convert.ToBoolean(t);
use this  code for convert object to Boolean

var t = propInfo.GetValue(item, null); bool state = Convert.ToBoolean(t);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM