Created
January 25, 2011 21:00
-
-
Save thecodejunkie/795650 to your computer and use it in GitHub Desktop.
implicit cast operators on the dynamicdictionaryvalue
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
namespace ConsoleApplication1 | |
{ | |
using System.Dynamic; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
dynamic dictionary = new DynamicDictionary(); | |
dictionary.foo = "test"; | |
dictionary.bar = Guid.NewGuid(); | |
var worker = new Worker(); | |
worker.DoWork(dictionary.foo, dictionary.bar); | |
Console.ReadLine(); | |
} | |
} | |
public class Worker | |
{ | |
public void DoWork(string value, Guid id) | |
{ | |
Console.WriteLine(value); | |
Console.WriteLine(id.ToString()); | |
} | |
} | |
public class DynamicDictionary : DynamicObject | |
{ | |
private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>(); | |
public override bool TrySetMember(SetMemberBinder binder, object value) | |
{ | |
this[binder.Name] = value; | |
return true; | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
return dictionary.TryGetValue(binder.Name, out result); | |
} | |
public dynamic this[string name] | |
{ | |
get { return dictionary[name]; } | |
set { dictionary[name] = value is DynamicDictionaryValue ? value : new DynamicDictionaryValue(value); } | |
} | |
} | |
public class DynamicDictionaryValue : DynamicObject | |
{ | |
public DynamicDictionaryValue(object value) | |
{ | |
Value = value; | |
} | |
private object Value { get; set; } | |
public static implicit operator string(DynamicDictionaryValue d) | |
{ | |
return Convert.ToString(d.Value); | |
} | |
public static implicit operator Guid(DynamicDictionaryValue d) | |
{ | |
return (Guid)d.Value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment