gpt4 book ai didi

没有 self 标识符的 F# Val

转载 作者:行者123 更新时间:2023-12-01 00:48:24 25 4
gpt4 key购买 nike

只是好奇为什么 F# 有:成员 val Foo = ... with get, set同时省略 self 标识符(例如 this.)。这仍然是一个实例属性。也许我是唯一一个在使用它时感到困惑的人。但只是让我很困扰,想问问知道该语言是如何定义的人。

最佳答案

使用这种语法,该属性几乎完全是自动实现的——您所提供的只是初始化代码,它基本上作为构造函数的一部分运行。

F# 实现的最佳实践保护措施之一是,它不允许您在实例完全初始化之前访问实例成员。 (哇,疯狂的想法,对吧?)。

因此,无论如何,您在 auto-props 中不会使用自标识符,因为您要编写的唯一代码是无法触及实例成员的初始化代码。

根据 MSDN 文档(强调我的):

Automatically implemented properties are part of the initialization of a type, so they must be included before any other member definitions, just like let bindings and do bindings in a type definition. Note that the expression that initializes an automatically implemented property is only evaluated upon initialization, and not every time the property is accessed. This behavior is in contrast to the behavior of an explicitly implemented property. What this effectively means is that the code to initialize these properties is added to the constructor of a class.

顺便说一句,如果你想成为一个聪明人并使用类级别的 self 标识符来解决这个问题,你仍然会在运行时崩溃:

type A() as this =
member val X =
this.Y + 10
with get, set

member this.Y = 42

let a = A()

System.InvalidOperationException: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
at Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicFunctions.FailInit()
at FSI_0013.A.get_Y()
at FSI_0013.A..ctor()
at <StartupCode$FSI_0014>.$FSI_0014.main@()

编辑: 值得注意的是,在即将推出的 C# 6 中,它们现在还允许使用初始化程序自动支持(更多 F# 功能被 C# 窃取,令人震惊 :-P),并且有一个类似的限制您不能使用 self 标识符:

class A
{
// error CS0027: Keyword 'this' is not available in the current context
public int X { get; set; } = this.Y + 10;
public int Y = 42;
public A() { }
}

关于没有 self 标识符的 F# Val,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29172119/

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