Skip to content

Instantly share code, notes, and snippets.

@masaedw
Created October 4, 2012 10:57
Show Gist options
  • Save masaedw/3832943 to your computer and use it in GitHub Desktop.
Save masaedw/3832943 to your computer and use it in GitHub Desktop.
C#でDynamicScope
[TestMethod]
public void DynamicScopeTest()
{
var x = new User { Name = "hoge" };
Assert.AreEqual("hoge", x.Name);
using (DynamicScope.Start(x, y => y.Name, "name"))
{
Assert.AreEqual("name", x.Name);
}
Assert.AreEqual("hoge", x.Name);
}
public static class DynamicScope
{
public static IDisposable Start<T, U>(T obj, Expression<Func<T, U>> expression, U value)
{
return new DynamicScope<T, U>(obj, expression, value);
}
}
class DynamicScope<TTarget, TValue> : IDisposable
{
Action<TTarget, TValue> WriteAction;
TTarget Target;
TValue Original;
public DynamicScope(TTarget obj, Expression<Func<TTarget, TValue>> expression, TValue value)
{
var rhs = Expression.Parameter(typeof(TValue), "value");
var body = expression.Body;
var assign = Expression.Assign(body, rhs);
var lhs = expression.Parameters[0];
var actionExp = Expression.Lambda<Action<TTarget, TValue>>(assign, lhs, rhs);
WriteAction = actionExp.Compile();
Original = expression.Compile()(obj);
Target = obj;
WriteAction(obj, value);
}
public void Dispose()
{
WriteAction(Target, Original);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment