DLR in .NET
March 2, 2010Bet this starts freaking people out sooner rather than later. I personally love it. Go duck typing. (and unit tests).
Looking at Ayende’s potential DB solution over Lucene and it’s peek my interest. I remember writing so much reflection code for dynamics and JSON, now its more or less out of the box.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Dynamic;
namespace Dynamics
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
dynamic d = new Bag();
d.Age = 25;
d.Name = "Terrance";
Action<dynamic> hi = (self) => Console.WriteLine("{0} is {1} years old!", self.Name, self.Age);
d.SayHello = hi;
// result = "Terrance is 25 years old!";
d.SayHello();
// result = "Terrance is 25 years old!";
SayHelloAgain(d);
}
void SayHelloAgain(dynamic d)
{
d.SayHello();
}
}
public class Bag : DynamicObject
{
Dictionary<string, object> _properties = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = _properties[binder.Name];
return _properties.ContainsKey(binder.Name);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_properties[binder.Name] = value;
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
dynamic target = _properties[binder.Name];
bool match = false;
result = null;
switch (args.Length)
{
case 0:
target(this);
match = true;
break;
}
return match;
}
}
}