简体   繁体   中英

Casting - What's the difference between “(myObject)something” and “something As myObject” in C#?

I've encountered this a couple of times and been perplexed.

Cat c = new Cat("Fluffy");
return (Animal)c;

Cat c = new Cat("Fluffy");
return c as Animal;

What's the reason for both of these syntaxes to exist?

The as operator is a safe cast. If the types are not compatible, as will return null .

The explicit cast, (Animal)c , on the other hand, will throw an InvalidCastException if the types are not assignment-compatible.

Also worth noting that as only works for inheritance relationships, whereas the explicit cast operator will work for value types...

decimal d = 4.0m;
int i = (int)d;

...and any other explicit conversion operators defined on the type with public static explicit operator . These won't work with as .

http://blogs.msdn.com/csharpfaq/archive/2004/03/12/88420.aspx

"Using the as operator differs from a cast in C# in three important ways:

1) It returns null when the variable you are trying to convert is not of the requested type or in it's inheritance chain, instead of throwing an exception.

2) It can only be applied to reference type variables converting to reference types.

3) Using as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do.

There are in fact two completely different operations defined in IL that handle these two keywords (the castclass and isinst instructions) - it's not just "syntactic sugar" written by C# to get this different behavior. The as operator appears to be slightly faster in v1.0 and v1.1 of Microsoft's CLR compared to casting (even in cases where there are no invalid casts which would severely lower casting's performance due to exceptions)."

With this:

return (Animal)c;

You are explicitly saying that c is of type animal, and if not something has gone wrong.

With this:

return c as Animal;

You are saying that you are pretty sure that c is of type animal, but maybe not all the time.

Eric Lippert talks about it in his blog:

http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx

The cast syntax, return (Animal)c; will throw an InvalidCastException if the object cannot be cast to the type Animal . This is nice if you know it is an Animal, and if it is not, something has gone very wrong.

The return c as Animal; syntax will return null. This is handy if you would like to avoid catching exceptions:

Cat c = GetAnimal("Fluffy");
if (c == null)
{
    AddAnimal("Fluffy");
}

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