Created
August 5, 2012 15:31
-
-
Save mgroves/3265408 to your computer and use it in GitHub Desktop.
Using C#'s dynamic to create a DynamicProxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // from: http://weblogs.asp.net/lichen/archive/2012/08/03/gave-a-presentation-on-c-dynamic-and-dynamic-language-runtime-dlr-at-socal-net-user-group-meeting.aspx | |
| // pros: no requirement for members to be virtual, no need for a 3rd party framework | |
| // cons: loss of static typing benefits (i.e. intellisense & compile time checking), not practical for IoC | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| dynamic myObj = new DynamicProxy(new MyClass()); | |
| myObj.Foo(); | |
| } | |
| } | |
| public class MyClass | |
| { | |
| public void Foo() | |
| { | |
| Console.WriteLine("foo"); | |
| } | |
| } | |
| public class DynamicProxy : DynamicObject | |
| { | |
| readonly object _target; | |
| public DynamicProxy(object target) | |
| { | |
| _target = target; | |
| } | |
| public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) | |
| { | |
| Console.WriteLine("before invoking " + binder.Name); | |
| result = _target.GetType().InvokeMember(binder.Name, BindingFlags.InvokeMethod, null, _target, args); | |
| Console.WriteLine("after invoking " + binder.Name); | |
| return true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks