Information Technology Reference
In-Depth Information
The compiler will use the specific version for any objects of type Product
or SpecialProduct (or any other product-derived class in your object model).
For anything else, the compiler will use the version statically typed as
dynamic. That includes anonymous types. Internally, the dynamic binder
will cache method info for each method it uses. That will minimize the over-
head for the likely case that you'll often be calling WritePricingInformation()
for the same anonymous type over and over. Once the method binding
has been performed on the first call, it will be reused on each subsequent
call. It's a nonzero cost, but the dynamic implementation does as much
work as possible to minimize the cost of using dynamic.
Yo u m a y b e w o n d e r i n g w h y n o n e o f t h e s e m e t h o d s a r e e x t e n s i o n m e t h o d s
so that they would appear to be members of the anonymous type. Well,
that would be great, but it's not legal C#. You are not allowed to create
extension methods that extend dynamic objects.
Yo u c a n l e v e r a g e d y n a m i c t o c r e a t e m e t h o d s t h a t a r e i n t e n d e d t o b e u s e d
with anonymous types. It's a technique to be used sparingly, like strong
spices. If you find yourself creating many methods using dynamic invoca-
tion that are intended for use with anonymous types, that's a strong indi-
cation that you should create a concrete type to represent that concept. It
will be much easier to maintain over time, and you'll have better support
from the compiler and the type system. However, when you need one or
two utility methods that use an anonymous type, dynamic invocation is a
simple way to create that behavior.
Item 41: Use DynamicObject or IDynamicMetaObjectProvider for
Data-Driven Dynamic Types
One great advantage of dynamic programming is the ability to build types
whose public interface changes at runtime, based on how you use them. C#
provides that ability through dynamic, the System.Dynamic.DynamicObject
base class, and the System.Dynamic.IDynamicMetaObjectProvider inter-
face. Using these tools, you can create your own types that have dynamic
capabilities.
The simplest way to create a type with dynamic capabilities is to derive from
System.Dynamic.DynamicObject. That type implements the IDynamic-
MetaObjectProvider interface using a private nested class. This private
nested class does the hard work of parsing expressions and forwarding those
to one of a number of virtual methods in the DynamicObject class. That
 
 
Search WWH ::




Custom Search