【发布时间】:2015-06-10 03:20:45
【问题描述】:
我在将谓词传递给另一个函数时遇到问题。该谓词将作为试图调用第二个函数的参数传入。下面是代码sn-p。
public IEnumerable<ViewModel> BuildModel<TPart, TRecord>(Expression<Func<TRecord, bool>> predicate)
where TPart : ContentPart<TRecord>
where TRecord : ContentPartRecord
{
IEnumerable<ReportPart> items = GetList<ReportPart, ReportRecord>(predicate);
这个问题是谓词参数,在调用GetList() 时一直出错,说调用有一些无效的参数。获取列表调用是:
public IEnumerable<TPart> GetList<TPart, TRecord>(Expression<Func<TRecord, bool>> predicate)
where TPart : ContentPart<TRecord>
where TRecord : ContentPartRecord
我一直在尝试以多种不同的方式更改参数以使其正常工作,但我没有取得任何成功。也许我不明白为什么编译器认为“谓词”与GetList() 所期望的不同。
编辑:更多信息
ReportPart : ContentPart<ReportRecord>
ReportRecord : ContentPartRecord
ContentPart 和 ContentPartRecord 都是基类
BuildModels 的调用者
List<ReportViewModel> model = _service.BuildReports<ReportPart, ReportRecord>(x => x.Id == 1).ToList();
构建模型
public IEnumerable<ReportViewModel> BuildReports<TPart, TRecord>(System.Linq.Expressions.Expression<Func<TRecord, bool>> predicate)
where TPart : ContentPart<TRecord>
where TRecord : ContentPartRecord
{
List<ReportViewModel> model = new List<ReportViewModel>();
IEnumerable<ReportPart> reportParts = GetList<ReportPart, ReportRecord>(predicate);
//do some stuff with reportParts
return model;
}
}
获取列表
public IEnumerable<TPart> GetList<TPart, TRecord>(System.Linq.Expressions.Expression<Func<TRecord, bool>> filter)
where TPart : ContentPart<TRecord>
where TRecord : ContentPartRecord
{
return filter == null ?
Services.ContentManager.Query<TPart, TRecord>().List() :
Services.ContentManager.Query<TPart, TRecord>().Where(filter).List();
}
【问题讨论】:
-
能否请您发布准确的错误信息?您还可以发布
ReportPart和ReportRecord的继承层次结构吗? -
根据您的错误消息,问题是由您传递给 BuildModel 的参数引起的。你怎么称呼它?
-
调用
GetList时没有出错。调用BuildModel时出错,您未在此处显示。 -
好吧,
BuildModel正在将Expression<Func<TRecord, bool>>传递给一个应该是Expression<Func<ReportRecord, bool>>的参数。我认为那行不通。委托协变和逆变是有限的,在这里,你不知道TRecord实际是什么类型。最重要的是,您将其包装在Expression中,这可能会使逆变根本不起作用。 -
协变和逆变不起作用。试试这条线
var items = GetList<TPart, TRecord>(predicate);应该可以工作。
标签: c# linq parameters predicate