gpt4 book ai didi

f# - 如何使用方法在 F# 的默认构造函数中设置属性

转载 作者:行者123 更新时间:2023-12-01 04:29:56 25 4
gpt4 key购买 nike

我正在尝试编写一个构造函数,假设调用类中定义的方法并将结果分配给成员。在 C# 中,它类似于:

public class Test
{
public int Value { get; private set;}

private static int SomeLogic(int a, int b)
{
return a + b;
}

public Test(int a, int b)
{
this.Value = SomeLogic(a,b);
}
}

但我不知道如何做到这一点 F#。

最佳答案

在 F# 中实现此目的的两种不同方法的示例:

type Test_UsesVal =
val value : int
new (a, b) = { value = someLogic a b }
member x.Value = x.value

type Test_Preferred (a : int, b: int) =
let value = someLogic a b
member x.Value = value

两个有缺点的例子:
// This type is default constructible and when using default ctor someLogic is not used
type Test_DefaultConstructible () =
let mutable value = 0
new (a, b) as x = Test_DefaultConstructible () then x.Value <- someLogic a b
member x.Value with get () = value and private set v = value <- v

// This type has 2 constructors and using single value ctor someLogic is not used
type Test_2Constructors (value : int) =
new (a, b) = Test_2Constructors (someLogic a b)
member x.Value with get () = value

由于提到了自引用类型,我只想指出,使类型自引用会增加隐藏的开销:
// Self referential types add hidden overhead
type Test_SelfReferential (a : int, b: int) as this =
let computeValue () = someLogic this.A this.B

member x.A = a
member x.B = b
member x.Value = computeValue ()

反编译开销显示:
[CompilationMapping(SourceConstructFlags.ObjectType)]
[Serializable]
public class Test_SelfReferential
{
internal int b;

internal int a;

// An extra field added
internal FSharpRef<Program.Test_SelfReferential> @this = new FSharpRef<Program.Test_SelfReferential>(null);

// An extra field added
internal int init@29-1;

public int A
{
get
{
// An extra check added in each method
if (this.init@29-1 < 1)
{
LanguagePrimitives.IntrinsicFunctions.FailInit();
}
return this.a;
}
}

public int B
{
get
{
// An extra check added in each method
if (this.init@29-1 < 1)
{
LanguagePrimitives.IntrinsicFunctions.FailInit();
}
return this.b;
}
}

public int Value
{
get
{
// An extra check added in each method
if (this.init@29-1 < 1)
{
LanguagePrimitives.IntrinsicFunctions.FailInit();
}
return this.computeValue();
}
}

public Test_SelfReferential(int a, int b) : this()
{
this.a = a;
this.b = b;
// An extra init added in .ctor
this.@this.contents = this;
this.init@29-1 = 1;
}

[CompilerGenerated]
internal int computeValue()
{
// Extra checks added
return LanguagePrimitives.IntrinsicFunctions.CheckThis<Program.Test_SelfReferential>(this.@this.contents).A + LanguagePrimitives.IntrinsicFunctions.CheckThis<Program.Test_SelfReferential>(this.@this.contents).B;
}
}

F# 中自引用类型的隐藏开销曾经导致我性能下降(在某些用例中性能下降了 50%)。

关于f# - 如何使用方法在 F# 的默认构造函数中设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44440694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com