Created
October 4, 2012 10:57
-
-
Save masaedw/3832943 to your computer and use it in GitHub Desktop.
C#でDynamicScope
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
[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