Information Technology Reference
In-Depth Information
typeof ( DynamicDictionary2 ).GetMethod(methodName),
parameters),
BindingRestrictions .GetTypeRestriction(Expression,
LimitType));
return getDictionaryEntry;
}
Before you go off and think this isn't that hard, let me leave you with some
thoughts from the experience of writing this code. This is about as simple
as a dynamic object can get. You have two APIs: property get , property
set . The semantics are very easy to implement. Even with this very sim-
ple behavior, it was rather difficult to get right. Expression trees are hard
to debug. They are hard to get right. More sophisticated dynamic types
would have much more code. That would mean much more difficulty get-
ting the expressions correct.
Furthermore, keep in mind one of the opening remarks I made on this
section: Every invocation on your dynamic object will create a new
DynamicMetaObject and invoke one of the Bind members. You'll need to
write these methods with an eye toward efficiency and performance. They
will be called a lot, and they have much work to do.
Implementing dynamic behavior can be a great way to approach some of
your programming challenges. When you look at creating dynamic types,
your first choice should be to derive from System.Dynamic.DynamicObject.
On those occasions where you must use a different base class, you can
implement IDynamicMetaObjectProvider yourself, but remember that
this is a complicated problem to take on. Furthermore, any dynamic types
involve some performance costs, and implementing them yourself may
make those costs greater.
Item 42: Understand How to Make Use of the Expression API
.NET has had APIs that enable you to reflect on types or to create code at
runtime. The ability to examine code or create code at runtime is very
powerful. There are many different problems that are best solved by
inspecting code or dynamically generating code. The problem with these
APIs is that they are very low level and quite difficult to work with. As
developers, we crave an easier way to dynamically solve problems.
Now that C# has added LINQ and dynamic support, you have a better way
than the classic Reflection APIs: expressions and expression trees. Expres-
 
 
Search WWH ::




Custom Search