加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

为什么VB不会阻止在现场初始化中使用“Me”,像C#与“this”一样

发布时间:2020-12-17 00:30:59 所属栏目:大数据 来源:网络整理
导读:在VB中你可以这样做: Class One Private myTwo As Two = New Two(Me)End ClassClass Two Sub New(withOne As One) End SubEnd Class 但是在C#中,你不能这样做: class One{ private Two myTwo = new Two(this);}class Two{ public Two(One withOne) { }} 因
在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 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 instance
method,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中,当初始化程序运行时,Me是一个有效的参考,但是在C#运行时,这还不是一个有效的参考.

Per Eric Lippert C#这样做,以便他们可以保证只读字段始终被初始化,然后才能被引用.

我没有看到它在任何地方明确表示,但如果我不得不猜测他们发现VB.NET中的缺陷,而C#仍在开发中;然后他们觉得这是一个足够大的问题,值得在C#中修复,但不是一个足够大的问题,可以使VB.NET发生变化(甚至是广泛的).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读