繁体   English   中英

在F#中使用C#流畅的库

[英]Using C# fluent library in F#

我试图在F Sharp样本中使用FluentValidation库。 但我陷入困境,因为我甚至无法将简单的C Sharp代码转换为F Sharp代码。

但后来我认为这个奇妙的库只是试图将编程方面的功能部分带到CSharp,所以我应该只在FSharp中创建自己的库,而不是使用它。 这将是简单和适当的方式。

所以,我需要一个意见,哪种方式会更好。 如果有人可以为此创建FSharp示例,那将会很棒。 它仅用于学习目的,因为我主要在C#中使用流畅的库。 而且我喜欢和他们一起去F#。

F#支持流畅的DSL,并且有几个F#库具有流畅的API。 F#的类型系统与C#有点不同,大多数差异都是用流畅的API弹出的,但是,这仍然有效:

#r @"C:\Users\Ramon\Downloads\FluentValidation\FluentValidation\FluentValidation.dll"

open System
open FluentValidation

type Customer =
    { Surname : string
      Forename : string
      Company : string
      Discout : int
      Address : string
      Postcode : string
      Discount : int
      HasDiscount : bool }

type IRuleBuilder<'T,'Property> with
    member __.Ignore = ()

type CustomerValidator =
    inherit AbstractValidator<Customer>

    new () =
        let beAValidPostcode postcode = true
        base.RuleFor(fun customer -> customer.Surname).NotEmpty().Ignore
        base.RuleFor(fun customer -> customer.Forename).NotEmpty().WithMessage("Please specify a first name").Ignore
        base.RuleFor(fun customer -> customer.Company).NotNull().Ignore
        base.RuleFor(fun customer -> customer.Discount).NotEqual(0).When(fun customer -> customer.HasDiscount).Ignore
        base.RuleFor(fun customer -> customer.Address).Length(20, 250).Ignore
        base.RuleFor(fun customer -> customer.Postcode).Must(beAValidPostcode).WithMessage("Please specify a valid postcode").Ignore
        { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM