I'm still trying to map my deep and old knowledge from C/C++ to my somewhat more shallow .Net knowledge. Today the time has come to "as" (and implicitly "is" and cast) in C#.
My mental model of "as" is that it's a QueryInterface
or dynamic_cast
(a dynamic_cast
with pointer ar开发者_StackOverflowgument, not reference, that is) for C#. My question is two-fold:
- Is my comparison fair?
- What's the relative cost of "as" compared to
QueryInterface
ordynamic_cast
?
Yes, the comparison is fair, especially when dealing with pointers. Each of the three either succeeds and returns a non-null pointer of the target type, or returns null.
You can actually use the
as
operator when working with COM objects in .NET, making it equivalent toQueryInterface
with a small amount of overhead for the managed/COM interop. Inside of the CLR (casting between managed types), theas
operator is extremely lightweight compared toQueryInterface
in COM ordynamic_cast
in C++. For all the places in my code where I had to use dynamic casting for some reason, I've never seen theas
operator show even one sample in profiling - and considering I maintain an implementation of a dynamically-typed, runtime-bound language (StringTemplate), I assume that means something. :)
精彩评论