Expression Tree ToString() method generates strange string WHY?

回眸只為那壹抹淺笑 提交于 2019-12-11 12:27:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!