gpt4 book ai didi

c# - 为什么 VB 不像 C# 使用 "Me"那样阻止在字段初始化中使用 "this"?

转载 作者:太空狗 更新时间:2023-10-29 17:40:11 24 4
gpt4 key购买 nike

在 VB 中你可以这样:

Class One
Private myTwo As Two = New Two(Me)
End Class

Class Two
Sub New(withOne As One)

End Sub
End Class

但在 C# 中,您不能这样做:

class One
{
private Two myTwo = new Two(this);
}

class Two
{
public Two(One withOne)
{

}
}

因为您收到错误消息“关键字‘this’在当前上下文中不可用”。

我找到了 this question/answer引用the C# language specification第 7.6.7 节:

7.6.7 This access

A this-access is permitted only in the block of an instance constructor, an instancemethod, or an instance accessor. ... (specifics omitted) ... Use of this in a primary-expression in a context other than the ones listed above is a compile-time error. In
particular, it is not possible to refer to this in a static method, a static property
accessor, or in a variable-initializer of a field declaration.

此外,this question涵盖了它(尽管根据我的选择,没有充分回答它),Oblivious Sage 在这里对我的问题的回答解释了原因——因为它具有防止错误的功能。

为什么这个功能被排除在 VB 之外?

最佳答案

this question 中所述,区别在于构造函数在 VB.NET 中运行之前字段初始值设定项,但在 C# 中之后字段初始值设定项。因此在 VB.NET 中 Me 在初始化器运行时是一个有效的引用,但在 C# 中 this 在它们运行时还不是一个有效的引用。

根据 Eric Lippert C# 这样做是为了保证只读字段在被引用之前总是被初始化。

我没有在任何地方看到它的明确说明,但如果我不得不猜测他们在 C# 仍在开发时就注意到了 VB.NET 中的缺陷;然后,他们认为这是一个值得在 C# 中修复的大问题,但还不足以对 VB.NET 进行重大(并且可能是广泛的)更改。

关于c# - 为什么 VB 不像 C# 使用 "Me"那样阻止在字段初始化中使用 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27407852/

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