我很失望地发现 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,但仍然强制验证?
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)
你怎么称呼第一个功能?
我正在尝试编写一个自定义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?