简体   繁体   English

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

[英]Using C# fluent library in F#

I was trying to use FluentValidation library in F Sharp sample. 我试图在F Sharp样本中使用FluentValidation库。 But I got stuck as I can't even turn a simple C Sharp code to F Sharp code. 但我陷入困境,因为我甚至无法将简单的C Sharp代码转换为F Sharp代码。

But then I thought that this wonderful library is just trying to bring functional bits of programming side to CSharp, so instead of using this I should create my own library in FSharp only. 但后来我认为这个奇妙的库只是试图将编程方面的功能部分带到CSharp,所以我应该只在FSharp中创建自己的库,而不是使用它。 That will be easy and appropriate way. 这将是简单和适当的方式。

So, I need a opinion in that, which way will be better. 所以,我需要一个意见,哪种方式会更好。 And if someone can create FSharp sample for this, that will be great. 如果有人可以为此创建FSharp示例,那将会很棒。 It is just for learning purpose as I mostly use fluent library in C#. 它仅用于学习目的,因为我主要在C#中使用流畅的库。 And I like to go with them in F#. 而且我喜欢和他们一起去F#。

F# supports fluent DSLs, and there are several F# libraries with a fluent API. F#支持流畅的DSL,并且有几个F#库具有流畅的API。 F#'s type system is a bit different from C#'s, and most of the differences pop-up with fluent APIs, but still, this works: 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