1
Expression<Action>
의 매개 변수 값에 액세스해야하는 식 분석 코드를 작성 중입니다.MemberExpression에서 폐쇄 형 지역 변수에 액세스하는 방법?
코드 아래의 파라미터는 소스 객체의 부재 또는 특성 때마다 작동하지만 부재는 근접 위에 로컬 변수 때 실패한다. 로컬 변수에 액세스 할 수 있도록 로컬 변수를 통해 닫는 익명 형식에 대한 액세스 권한을 얻으려면 어떻게해야합니까?
Test method FluentCache.Test.ClosureTest.Test threw exception:
System.ArgumentException: Field 'localVariable' defined on type 'Test.ClosureTest+<>c__DisplayClass2' is not a field on the target object which is of type 'Test.ClosureTest'
여기에 간단한 코드입니다 :
[TestMethod]
public void Test()
{
Func<int, int> myAction = i => i + 1;
int localVariable = 10;
int analyzed = (int)GetFirstParameterValue(this,() => myAction(localVariable));
Assert.AreEqual(localVariable, analyzed);
}
public object GetFirstParameterValue(object source, Expression<Action> expression)
{
var invocationExpression = expression.Body as InvocationExpression;
var parameterExpression = invocationExpression.Arguments[0] as MemberExpression;
var parameterFieldInfo = parameterExpression.Member as FieldInfo;
//ERROR: This code will fail because the local variable is "wrapped" in a closure anonymous type
//How do I get access to the anonymous type in order to retrieve the value?
object fieldValue = parameterFieldInfo.GetValue(source);
return fieldValue;
}