C#重构函数使用泛型和lambda

时间:2018-03-20 03:57:23

标签: c# generics lambda fluentvalidation

我正在尝试重构一些在几个方面会有类似的代码。这段代码来自使用fluentvalidation的验证器。我正在尝试将HaveUniqueNumber例程转换为通用的,并传入将在db查询中使用的lambdas。

public class AddRequestValidator : AbstractValidator<AddRequest>
{
    public AddRequestValidator()
    {
        RuleFor(x => x)
            .Must(x => HaveUniqueNumber(x.myNumber, x.parentId))
            .WithMessage("myNumber '{0}' already exists for parentId '{1}'.", x => x.myNumber, x=>x.parentId);
    }

    private bool HaveUniqueNumber(string number, int parentId)
    {
        myModel existingNumber = null;

        using (var context = new myContextDb())
        {
            existingNumber = context.myModel.SingleOrDefault(a => a.MyNumber == number && a.ParentId == parentId);
        }

        return existingNumber == null;
    }
}

我尝试实现类似的东西:

public class AddRequestValidator : AbstractValidator<AddRequest>
{
    public AddRequestValidator()
    {
        RuleFor(x => x)
            .Must(x => HaveUniqueNumber<myModel>(an => an.myNumber == x.MyNumber, an => an.parentId == x.parentId))
            .WithMessage("myNumber '{0}' already exists for parentId '{1}'.", x => x.myNumber, x=>x.parentId);
    }

    private bool HaveUniqueNumber<T>(Expression<Func<T, bool>> numberExpression, Expression<Func<T, bool>> parentExpression)
    {
        T existingNumber = default(T);

        using (var context = new myContextDb())
        {
            existingNumber = context.T.SingleOrDefault(numberExpression && parentExpression);
        }

        return existingNumber == null;
    }
}

我怎样才能得到与原作相似的东西。

1 个答案:

答案 0 :(得分:1)

需要修复以下内容:

if let indexPath = self.tableView.indexPathForSelectedRow { // test to see if i can store row name in the defaults array let defaults = UserDefaults.standard var myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]() if let datastring = TableData[indexPath.row] as? String { if !myarray.contains(datastring) { myarray.append(datastring) defaults.set(myarray, forKey: "SavedStringArray") defaults.synchronize() } } } context.T

添加了由Alexei Levenkov发布的链接引用的ExpressionVisitor类。 457316

context.DbSet<T>()添加到HaveUniqueMethod

结束了这个重构的课程:

where T: class

并添加了此扩展方法:

private bool HaveUniqueNumber<T>(Expression<Func<T, bool>> numberExpression, Expression<Func<T, bool>> parentExpression) where T : class
{
    T existingNumber = default(T);

    using (var context = new myContextDb())
    {
        existingNumber = context.Set<T>().SingleOrDefault(numberExpression.AndAlso(parentExpression));
    }

    return existingNumber == null;
}