小编Mur*_*ray的帖子

防止 C#“with 表达式”绕过构造函数验证

我很失望地发现 C# 的“with 表达式”允许调用者绕过记录上的构造函数验证。

考虑:

record AscendingPair { 
    public AscendingPair(int small, int large)
    {
        if (small >= large) throw new ArgumentException("");
        (Small, Large) = (small, large);
    }
    public int Small { get; init; }
    public int Large { get; init; }
}

[Test]
public void Can_create_an_invalid_pair() {
    var valid = new AscendingPair(1, 2);
    var invalid = valid with { Small = 3 }; // This does not throw :(
}
Run Code Online (Sandbox Code Playgroud)

是否有一个聪明的解决方法可以允许使用with,但仍然强制验证?

c#

21
推荐指数
1
解决办法
1023
查看次数

使用可选参数区分f#重载函数

F#允许重载函数仅由可选参数区分,例如:

type MyClass() = 
    member this.func(a: string, b:string) = "func(a,b)"
    member this.func(a: string, ?b:string) = "func(a,?b)"
Run Code Online (Sandbox Code Playgroud)

你怎么称呼第一个功能?

f#

7
推荐指数
1
解决办法
165
查看次数

如何实现DivideByInt

我正在尝试编写一个自定义DivideByInt,如下所示

type Pair = Pair of int * int with
    static member DivideByInt pair int = pair


[<EntryPoint>]
let main argv =
    LanguagePrimitives.DivideByInt (Pair(1,2)) 1 
    |> ignore 
    0

// compiler error: "FS0001: Method or object constructor 'DivideByInt' not found"
Run Code Online (Sandbox Code Playgroud)

为什么编译器找不到Pair.DivideByInt?

f#

3
推荐指数
1
解决办法
88
查看次数

标签 统计

f# ×2

c# ×1