这种灵活的“自我识别符”有什么好处?在 F# 中?
虽然我理解 F# 中的自我标识符,但我对这种好处感到困惑灵活性。为什么 F# 不像 C# 那样只支持 this.Blah
并结束它?我猜有些人用它来提高可读性,但即使这样似乎也有些牵强。那么,这种语言特性的用途/好处是什么?
对于不懂的人来说,下面是一个定义类型范围自身标识符“self”和方法范围标识符“this”的示例。该示例取自上面链接的 MSDN 文章。
type MyClass2(dataIn) as self =
let data = dataIn
do
self.PrintMessage()
member this.PrintMessage() =
printf "Creating MyClass2 with Data %d" data
While I understand self-identifiers in F#, I am puzzled as to the benefits of such flexibility. Why does F# not just support this.Blah
as C# does and be done with it? I'm guessing some people use it to improve readability, but even that seems a stretch. So, what are the uses/benefits of this language feature?
For the un-initiated, below is an example that defines a type-wide self identifier "self" and a method scoped identifier "this". The example is taken from the MSDN article linked above.
type MyClass2(dataIn) as self =
let data = dataIn
do
self.PrintMessage()
member this.PrintMessage() =
printf "Creating MyClass2 with Data %d" data
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个小优点是,您可以使用它们来区分对象表达式的
this
和创建它的类型:一个潜在的哲学原因是它使它看起来像
this
code> 引用与任何其他参数没有太大不同。如果您应该能够命名其他参数(而不是被迫使用 arg1、arg2 等),那么为什么您不能命名第一个论点也随你所欲吗?One small advantage is that you can use them to differentiate an object expression's
this
from that of the type which has created it:A potential philosophical reason is that it makes it seem like the
this
reference is not too different from any other argument. If you should be able to name the other arguments (instead of being forced to usearg1
,arg2
, etc.), then why shouldn't you be able to name the first argument as you please, too?我唯一能想到的(而且它并不大)是,由于在调用实例方法时必须显式引用自标识符,因此能够命名它可以让您使用比单词
this< 短的东西/代码>。 F# 所基于的 FP 语言中存在很多(无论是否有效)对简洁性的渴望(有时甚至到了过分的地步),这可能促使了这一点。毕竟,您会注意到这种愿望在 F# 中的其他地方表现出来,而在 C# 中则不会——注意像
iteri
这样的函数名称,可能会被称为IterateWithIndex
在 C# 中。The only thing I can come up with (and it's not big) is that since the self-identifier must explicitly be referred to when calling an instance method, being able to name it lets you use something shorter than the word
this
. There is a lot of (valid or not) desire in languages on FP languages on which F# is based for conciseness (sometimes to the point of overdoing it) that may have prompted this. After all, you'll note this desire showing through in other places in F# where it wouldn't in e.g. C#--note function names likeiteri
that would probably be calledIterateWithIndex
in C#.