繁体   English   中英

将字符串转换为 Func<T,Object>

[英]Convert string to Func<T,Object>

我有以下方法

     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);

它不起作用错误:您不能使用“System.String”类型的表达式来分配“ServicesLogModel”类型

编辑:方法签名

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);
        }
    }

问候

嗯,最终的解决方案是这样的

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();
    }

由于您的方法需要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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM