Information Technology Reference
In-Depth Information
makes it a relatively simple exercise to create a dynamic class, if you can
derive from DynamicObject.
For example, consider a class that implemented a dynamic property bag.
When you first create the DynamicPropertyBag, it doesn't have any items,
and therefore it doesn't have any properties. When you try to retrieve any
property, it will throw an exception. You can add any property to the bag
by calling the setter on that property. After adding the property, you can
call the getter and access any of the properties.
dynamic dynamicProperties = new DynamicPropertyBag ();
try
{
Console .WriteLine(dynamicProperties.Marker);
}
catch (Microsoft.CSharp.RuntimeBinder. RuntimeBinderException )
{
Console .WriteLine( "There are no properties" );
}
dynamicProperties.Date = DateTime .Now;
dynamicProperties.Name = "Bill Wagner" ;
dynamicProperties.Title = "Effective C#" ;
dynamicProperties.Content = "Building a dynamic dictionary";
The implementation of the dynamic property bag requires overriding the
Tr y S e t Me m b e r a n d Tr y G e t Me m b e r m e t h o d s i n t h e D y n a m i c O b j e c t b a s e
class.
class DynamicPropertyBag : DynamicObject
{
private Dictionary < string , object > storage =
new Dictionary < string , object >();
public override bool TryGetMember( GetMemberBinder binder,
out object result)
{
if (storage.ContainsKey(binder.Name))
{
result = storage[binder.Name];
return true ;
}
 
Search WWH ::




Custom Search