问题
I need string conversion of an Expression Tree so
I create an Expression Tree and use ToString method like this
var exp = ((Expression<Func<UserDetailInfo, bool>>) (x => x.OperationID == operationId)).ToString();
but result is strange
x => (x.OperationID == value(TCS.Proxy.PermissionProxy+<>c__DisplayClass5).operationId)
TCS.Proxy.PermissionProxy is my class in WCF proxy project !!! (I send expression from client to proxy)
but when I create this Expression myself everything is good
var entity = Expression.Parameter(typeof(UserDetailInfo));
var constant = Expression.Constant(operationId);
var e = Expression.Equal(Expression.Property(entity, "OperationID"), constant);
var exp = Expression.Lambda<Func<UserDetailInfo, bool>>(e, entity).ToString();
and result is ok
Param_0 => (Param_0.OperationID == operationId) // I Need this
How I can use ToString() can generates result like above ?
Why two results is different ?
* I Convert Expression to String for transfer it from client to WCF service so I need correct string for convert in server side from string to Expression
回答1:
This is because your right hand side member is not a constant, it is a captured variable. The TCS.Proxy.PermissionProxy+<>c__DisplayClass5
part means in the class TCS.Proxy.PermissionProxy
it had to create 5 new classes that holds values that where passed in via variable capture and this specific lambda uses the 5th one it created.
Your code (You never show your function so I made some guesses)
namespace TCS.Proxy
{
class PermissionProxy
{
public void SomeFunction()
{
int operationId = 0;
var exp = ((Expression<Func<UserDetailInfo, bool>>) (x => x.OperationID == operationId)).ToString()
}
}
}
Is getting re-written to something similar (It's actually a lot different but this example gets the point across) to
namespace TCS.Proxy
{
public class PermissionProxy
{
private class c__DisplayClass5
{
public int operationId;
}
public void SomeFunction()
{
int operationId = 0;
var <>c__DisplayClass5 = new c__DisplayClass5();
<>c__DisplayClass5.operationId = operationId;
var exp = ((Expression<Func<UserDetailInfo, bool>>) (x => x.OperationID == <>c__DisplayClass5.operationId)).ToString()
}
}
}
Which is different than what you manually created. If you want to "unbox" these custom classes you will need to write up a ExpressionVisitor that will go through the expression and re-write it in to the form you want to go over the wire.
来源:https://stackoverflow.com/questions/23459981/expression-tree-tostring-method-generates-strange-string-why