如何为多个表创建Generic方法? 我的桌子:
我需要使用Generic Method搜索它们。我尝试了以下内容:
呼叫:
var predicateSearchCustomer = GetSearchPredicate<Customer>(search,Types.Customer);
var predicateSearchEmployee = GetSearchPredicate<Employee>(search,Types.Employee);
我的方法:
public Expression<Func<T, bool>> GetSearchPredicate<T>(string parametrs, Types Types)
{
var predicateInner = PredicateBuilder.False<T>();
var paramertsForSearch = new List<string>(parametrs.Split(' '));
paramertsForSearch.RemoveAll(string.IsNullOrEmpty);
foreach (var item in paramertsForSearch)
{
var itemSearch = item;
switch (Types)
{
case Types.Customer:
predicateInner = predicateInner.Or(x => x.CustomerName.Contains(itemSearch));
predicateInner = predicateInner.Or(x => x.CustomerFamily.Contains(itemSearch));
break;
case Types.Employee:
predicateInner = predicateInner.Or(x => x.EmployeeName.Contains(itemSearch));
predicateInner = predicateInner.Or(x => x.EmployeeFamily.Contains(itemSearch));
break;
}
}
return predicateInner;
}
错误:
错误5'T'不包含'CustomerName'的定义,不包含 扩展方法'CustomerName'接受'T'类型的第一个参数 可以找到(你错过了使用指令或程序集 引用?)
如何将T
转换为Customer
或Employee
?
答案 0 :(得分:2)
如果必须根据传递给泛型方法的类型编写switch语句来执行不同的操作,那么您的方法不是通用的。所以写两种方法。代码将更易于阅读(并将编译为额外的奖励)。
话虽如此,你的方法可以改写成通用的:
public Expression<Func<T, bool>> GetSearchPredicate<T>(string parameters,
Func<T, string, bool> test1,
Func<T, string, bool> test2)
{
var predicateInner = PredicateBuilder.False<T>();
var paramertsForSearch = new List<string>(parametrs.Split(' '));
paramertsForSearch.RemoveAll(string.IsNullOrEmpty);
foreach (var item in paramertsForSearch)
{
var itemSearch = item;
predicateInner = predicateInner.Or(x => test1(x, itemSearch));
predicateInner = predicateInner.Or(x => test2(x, itemSearch));
}
return predicateInner;
}
var predicateSearchCustomer =
GetSearchPredicate<Customer>(search,
(cust, term) => cust.CustomerName.Contains(term),
(cust, term) => cust.CustomerFamily.Contains(term));
var predicateSearchEmployee =
GetSearchPredicate<Employee>(search,
(empl, term) => empl.EmployeeName.Contains(term),
(cust, term) => empl.EmployeeFamily.Contains(term));