Created
December 30, 2013 08:08
-
-
Save regionbbs/8179211 to your computer and use it in GitHub Desktop.
DynamicObject sample code
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Dynamic; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace DynamicObjectExample2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
dynamic d = CreateDynamicObject(); | |
Console.WriteLine("Prop1: {0}", d.Prop1); | |
Console.WriteLine("Prop2: {0}", d.Prop2); | |
Console.WriteLine("Prop3: {0}", d.Prop3); | |
d.InvokeVoid(); | |
var e = d.InvokeAdd(1, 2); | |
Console.WriteLine("e={0}", e); | |
Console.Read(); | |
} | |
static dynamic CreateDynamicObject() | |
{ | |
dynamic d = new MyDynamicObject(); | |
// assign property | |
d.Prop1 = 1; | |
d.Prop2 = 2; | |
d.Prop3 = 3; | |
// assign void method. | |
d.InvokeVoid = new Action(() => Console.WriteLine("InvokeVoid.")); | |
// assign returnable method. | |
d.InvokeAdd = new Func<int, int, int>((a, b) => a + b); | |
return d; | |
} | |
} | |
public class MyDynamicObject : DynamicObject | |
{ | |
private IDictionary<string, object> _objectMembers = new Dictionary<string, object>(); | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
if (!this._objectMembers.ContainsKey(binder.Name)) | |
{ | |
result = null; | |
return false; | |
} | |
else | |
{ | |
result = this._objectMembers[binder.Name]; | |
return true; | |
} | |
} | |
public override bool TrySetMember(SetMemberBinder binder, object value) | |
{ | |
if (!this._objectMembers.ContainsKey(binder.Name)) | |
{ | |
this._objectMembers.Add(binder.Name, value); | |
return true; | |
} | |
else | |
{ | |
this._objectMembers[binder.Name] = value; | |
return true; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment