0

如何为多个表创建通用方法?我的桌子:

  1. 顾客
  2. 员工

我需要使用通用方法搜索它们。我尝试了以下方法:

称呼:

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”的定义,并且找不到接受“T”类型的第一个参数的扩展方法“CustomerName”(您是否缺少 using 指令或程序集引用?)

如何转换TCustomeror Employee

4

1 回答 1

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));
于 2013-11-01T11:53:52.213 回答