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

kun*_*jee 6 c# f# fluentvalidation c#-to-f#

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

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

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

Ram*_*nir 8

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
        { }
Run Code Online (Sandbox Code Playgroud)

  • @StephenSwensen绝对在F#3 LINQ表达式中隐含地按照C#3开始工作:)这也意味着你可以使用基于LINQ表达式的其他C#库,如[Moq](http://trelford.com/blog/post/Moq.aspx ) (3认同)