Created
December 29, 2014 17:30
-
-
Save kcuzner/3670e78ae1707a0e959d to your computer and use it in GitHub Desktop.
ExpandoObject-esque DynamicObject ToString overriding
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.Linq; | |
using System.Dynamic; | |
using System.Collections.Generic; | |
namespace Expando | |
{ | |
public delegate string ToStringFunc(); | |
class ToStringExpandoObject : DynamicObject | |
{ | |
public IDictionary<string, object> Members { get; private set; } | |
public ToStringExpandoObject() | |
{ | |
this.Members = new Dictionary<string, object>(); | |
} | |
public override bool TryDeleteMember(DeleteMemberBinder binder) | |
{ | |
return this.Members.Remove(binder.Name); | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
return this.Members.TryGetValue(binder.Name, out result); | |
} | |
public override bool TrySetMember(SetMemberBinder binder, object value) | |
{ | |
this.Members[binder.Name] = value; | |
return true; | |
} | |
public override string ToString() | |
{ | |
//see if we defined a ToString member | |
//if not, use the base implementation | |
object methodObj; | |
this.Members.TryGetValue("ToString", out methodObj); | |
ToStringFunc method = methodObj as ToStringFunc; | |
if (method == null) | |
return base.ToString(); | |
return method(); | |
} | |
} | |
class MainClass | |
{ | |
public static void Main(string[] args) | |
{ | |
dynamic test = new ToStringExpandoObject(); | |
test.ToString = new ToStringFunc(() => | |
{ | |
return "Test"; | |
}); | |
test.Asdf = "asdf"; | |
Console.WriteLine(test); | |
Console.WriteLine(test.ToString()); | |
Console.WriteLine(test.Asdf); | |
test = new ToStringExpandoObject(); | |
Console.WriteLine(test); | |
Console.WriteLine(test.ToString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A big thank you for that :-) I used it in my open source XmlSlurper (https://github.com/dandraka/XmlUtilities/) and it was a life saver :-)