Gieno  Dynamic in C# 4.0, Part 8

After 7 posts on dynamic for learning, this time I think it's much more to fun to use it for something evil… by making Reflection simple.
In C# 3.0 invoking members through reflection, was kind of odd and certainly not very readable.
var employee = new Employee();
var members 
= employee.GetType().GetMember( "age", MemberTypes.All,              
                                                                  BindingFlags.IgnoreCase 
| BindingFlags.Instance |
                                                                  BindingFlags.NonPublic 
| BindingFlags.Public );
((FieldInfo)members[
0]).SetValue(employee, 30);
By wrapping all reflection magic in a dynamic object the same call would look like:
var employee = (new Employee()).AsDynamic();
employee.Name 
= "Gieno Miao";
employee.Age 
= 26;
Console.WriteLine(
"Employee {0} is {1} years old.", employee.Name, employee.Age);
How this works is relatively easy.. by deriving a wrapper class from the new DynamicObject and overriding the TrySetMember and TryGetMember object to do the dirty work for you.
Demo Code
As always, happy coding.

 posted on 2009-09-16 14:35  Gieno  阅读(1724)  评论(8编辑  收藏  举报