将字符串转换为Func <t,object>

时间:2015-09-22 17:03:16

标签: c# linq lambda expression-trees

我有以下方法

     public List<ServicesLogModel> Paging(Func<ServicesLogModel, bool> condition, string columnOrder, bool? orderDescending, int? pageIndex, int? pageSize, out int total)
    {
         return _mongoRepository.Paging(condition, order => order.Message, orderDescending.Value, pageIndex.Value, pageSize.Value, out total);
    }

columnOrder参数是一个字符串,作为lambda表达式(例如:order => order.Message),我必须强制转换为Func<T, object>

我尝试使用Expression.Parameter

 var parm = Expression.Parameter(typeof(ServicesLogModel), "order");

        var propName = Expression.Property(parm, columnOrder);

        Expression predicateBody = Expression.Assign(parm, propName);


        var test=Expression.Lambda<Func<ServicesLogModel, object>>(predicateBody, parm);

它没有用 错误:您不能使用类型为&#39; System.String&#39;的表达式。用于键入&#39; ServicesLogModel&#39;

的作业

编辑:方法签名

public List<T> Paging(Func<T, bool> condition, Func<T, object> order, bool orderDescending, int pageIndex, int pageSize,out int total) 

通话方法

    [HttpGet]
    [Route("Admin/GetReaderConnectorLog/{Apikey}/{SecretKey}/{index}/{pagesize}/{orderAsc}/{columnOrder}")]
    public IActionResult GetReaderConnectorLog(string Apikey, string SecretKey, int? index, int? pagesize, bool? orderAsc, string columnOrder)
    {
        try
        {
            _userService.BeginTransaction();
            //  _webApiHelper.ValidateApiKey(Apikey, SecretKey, Context, _userService, true);
            int total;
            //TEST
            var listModel = _connectorLogService.Paging(_ => true, $"order => order.{columnOrder}", orderAsc, index, pagesize, out total);
            _userService.Commit();
            return _webApiHelper.OkResponse($"{_appSettings.Options.UserTag}[Send List User]", Context, new PaginationModel<ServicesLogModel> { ListData = listModel, Total = total, Apikey = Apikey, SecretKey = SecretKey });
        }
        catch (Exception e)
        {
            _userService.Rollback();
            return _webApiHelper.ResolveException(Context, e);
        }
    }

此致

2 个答案:

答案 0 :(得分:2)

嗯,最终解决方案就是这个

public Func<T, object> GetLambda<T>(string property)
    {
        var param = Expression.Parameter(typeof(T), "p");

        Expression parent = Expression.Property(param, property);

        if (!parent.Type.IsValueType)
        {
            return Expression.Lambda<Func<T, object>>(parent, param).Compile();
        }
        var convert = Expression.Convert(parent, typeof(object));
        return Expression.Lambda<Func<T, object>>(convert, param).Compile();
    }

答案 1 :(得分:1)

由于您的方法需要Func<T,object>而不是Expression<Func<T,object>>,因此一个简单的解决方案是使用反射:

public Func<T, object> GetPropertyFunc<T>(string property_name)
{
    return t => typeof (T).GetProperty(property_name).GetMethod.Invoke(t, new object[] {});
}

此方法采用属性的名称,并返回所需的函数。

以下是测试方法:

ServicesLogModel model = new ServicesLogModel()
{
    Message = "my message"
};

Func<ServicesLogModel, object> func = GetPropertyFunc < ServicesLogModel>("Message"); //I am assuming the property name is "Message", but you can pass any string here

var message = func(model) as string;