c# - Lambda Func<> 和 Fluent

标签 c# lambda fluent-interface

现在有很多 Fluent 实现可以与 Lambda 一起使用来完成非常简洁的事情。我想全神贯注,这样我就可以开始创造其中的一些东西,但我还没有找到我的大脑能理解的解释。

考虑这个简单的 Person Validator 示例

public class PersonValidator : IValidator<Person>
{
     public PersonValidator()
     {
          AddRule(p => p.FirstName).CannotBeNull().CannotBeBlank();
          AddRule(p => p.LastName).CannotBeNull().CannotBeBlank();
     }

     public List<ValidationResult> Validate(Person p)
     {
         // pseudo...
         apply all rules specified in constructor, return results
     }
}

我已经设法在我的验证器上使用这样的方法来完成所有这些工作......

public ValidationResult<T,TProp> AddRule<T,TProp>(Func<T,TProp> property)
{
    ... not sure what to do here.  This method gives me the ability to use the lambda
    ... for specifying which properties i want to validate
}

然后我可以创建扩展方法来扩展 IValidator 以达到 CannotBeNull 和 CannotBeEmpty 的目的。

看来我有前半部分和后半部分的问题,但我不确定如何将它们组合在一起。

寻找有意义的解释......我想“明白”。 :)

最佳答案

流畅接口(interface)的关键是 CannotBeNull() 和 CannotBeBlank() 等方法返回当前实例(即 this)。如果您希望您的 AddRule 方法“流畅”,而不是返回 ValidationResult,您需要返回 IValidator 的当前实例。您的扩展方法还需要返回它们正在扩展的 IValidator 实例。

我认为您的具体实现可能需要更复杂一些,希望下面的示例能够提供一些见解。然而,相同的一般规则......返回“this”以创建流畅的界面:

interface IValidator<T>
{
    IValidatorRule<T, TProp> AddRule<TProp>(Func<T, TProp> property);
}

interface IValidatorRule<T>
{
    T instance { get; }
    string PropertyName { get; }

    ValidationResult Apply(T instance);
}

public static IValidatorAugmentorExtensions
{
    public static IValidatorRule<T> CannotBeNull(this IValidatorRule<T> rule)
    {
        // ...

        return rule;
    }

    public static IValidatorRule<T> CannotBeBlank(this IValidatorRule<T> rule)
    {
        // ...

        return rule;
    }
}

上面的可以这样使用:

public class PersonValidator: IValidator<Person>
{
    public PersonValidator()
    {
        AddRule(p => p.FirstName).CannotBeNull().CannotBeEmpty();
        AddRule(p => p.LastName).CannotBeNull().CannotBeEmpty();
    }    

    public List<ValidationResult> Validate(Person p)
    {
        List<ValidationResult> results = new List<ValidationResult>();

        foreach (IValidatorRule<Person> rule in rules) // don't know where rules is, or what the AddRule method adds to...you'll need to figure that out
        {
            results = rule.Apply(p);
        }

        return results;
    }
}

虽然上面演示了如何创建流畅的界面,但我真的不知道从长远来看,在这种特定情况下它会给你带来什么。为了方便一个似乎只在内部用于具体验证器的流畅接口(interface),您已经相当大地增加了代码的复杂性,而没有真正为验证器的使用者提供有用的、流畅的接口(interface)。我认为,通过为需要执行验证的开发人员提供流畅的验证框架,而不是为创建具体验证器提供流畅的框架,您会获得更多值(value)。

关于c# - Lambda Func<> 和 Fluent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1309931/

相关文章:

c# - 为什么要使用流畅的界面?

entity-framework - Entity Framework Code First 是否允许在单独的文件中进行流畅的映射?

c# - 记录错误,然后将其打印出来

lambda - 查找 Prolog 对列表中的键

c# - 转换为 void 返回委托(delegate)的匿名函数无法返回值

PHP 方法链还是流利的接口(interface)?

c# - 在 asp.net 中从 Web.config 获取连接字符串

c# - 调试时VSCode Asp.Net核心命令行参数?

c# - 我应该为域和 EF 使用单独的模型吗?

lambda - Racket 中 lambda 函数的求值顺序