Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Last active February 20, 2020 21:59
Show Gist options
  • Save JimBobSquarePants/f75ac4439eff0eaa22b061c5c4d37c1e to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/f75ac4439eff0eaa22b061c5c4d37c1e to your computer and use it in GitHub Desktop.
You can do really crazy things with C#
public class TypeWrapper
{
private readonly dynamic dyn;
private readonly Dictionary<string, CallSite<Action<CallSite, object, object>>> setters
= new Dictionary<string, CallSite<Action<CallSite, object, object>>>();
private readonly Dictionary<string, CallSite<Func<CallSite, object, object>>> getters
= new Dictionary<string, CallSite<Func<CallSite, object, object>>>();
public TypeWrapper(object d)
{
this.dyn = d;
Type type = d.GetType();
foreach (var p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
string name = p.Name;
CallSite<Action<CallSite, object, object>> set = CallSite<Action<CallSite, object, object>>.Create(
Microsoft.CSharp.RuntimeBinder.Binder.SetMember(
CSharpBinderFlags.None,
name,
type,
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) ,
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
this.setters.Add(name, set);
CallSite<Func<CallSite, object, object>> get = CallSite<Func<CallSite, object, object>>.Create(
Microsoft.CSharp.RuntimeBinder.Binder.GetMember(
CSharpBinderFlags.None,
name,
type,
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
this.getters.Add(name, get);
}
}
public void Set(string name, object value)
{
var set = this.setters[name];
set.Target(set, this.dyn, value);
}
public object Get(string name)
{
var get = this.getters[name];
return get.Target(get, this.dyn);
}
}
@MatthewOverall
Copy link

How can you make this work for nested properties?

@jaypaw549
Copy link

jaypaw549 commented Feb 20, 2020

Way old, but it might be faster if you change the dyn field to an object instead of dynamic. That way it doesn't compile like this.

EDIT: Note the use of dynamic binding in your Get and Set functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment