Last active
February 20, 2020 21:59
-
-
Save JimBobSquarePants/f75ac4439eff0eaa22b061c5c4d37c1e to your computer and use it in GitHub Desktop.
You can do really crazy things with C#
This file contains hidden or 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
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); | |
} | |
} |
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
How can you make this work for nested properties?