VB.NET 中的静态/共享和 C# 可见性 [英] static/Shared in VB.NET and C# visibility

查看:18
本文介绍了VB.NET 中的静态/共享和 C# 可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 VB.NET 和 C# (.NET2) 中遇到了静态/共享成员可见的情况.在我看来,在 VB.NET 中有点奇怪:

I have faced with a situation in VB.NET and C# (.NET2) with the visibility of the static/shared members. It seems to me a little strange in VB.NET:

    public class A 
    {
        private static A instance;
        public static A Instance 
        {
            get { return instance; }
        }

        public string Name { get { } }
    }

用法:A.Instance.Name//只有名称是可见的"

VB.NET:

Public Class A
  Private Shared _instance As A

  Public Shared ReadOnly Property Instance() As A
    Get
      Return _instance
    End Get
  End Property


  Public ReadOnly Property Name() As String
    Get
      Return ""
    End Get
  End Property

End Class

用法:

A.Instance.Instance.Instance.Instance...

//共享成员的行为就像一个公共类,我可以无限重复..

这是 Microsoft 的疏忽还是 VB.NET 的功能"?

is this a Microsoft oversight or a VB.NET "feature"?

推荐答案

这不是疏忽,但您的 VB 代码触发警告,这显然意味着:不要使用此符号.

It's not an oversight but your VB code will trigger a warning, which plainly means: do not use this notation.

在VB中,静态成员可以通过实例访问,因为严格来说,VB没有static:VB有关键字Shared,意味着成员在所有实例之间共享,而不是static,其中成员不属于any 实例.

In VB, static members can be accessed via an instance, since strictly speaking, VB doesn’t have static: VB has the keyword Shared, meaning that the member is shared between all instances, as opposed to static where a member doesn’t belong to any instance.

现在,这是这些关键字之间的语义区别.碰巧这两种不同的语义往往具有完全相同的效果.

Now, this is a semantical distinction between those keywords. It just so happens that these two distinct semantics tend to have the exact same effect.

当然,现在 C# 中的 static 与 VB.NET 中的 Shared 相同,但它们的遗产不同,VB 的 Shared 只是有一个不同的历史,因此在历史上有不同的意义.有了 this 的含义,通过实例访问 Shared 成员是绝对有意义的.

Of course, static in C# is today identical to Shared in VB.NET but their legacy is different and VB’s Shared simply has a different history and therefore historically a different meaning. With this meaning, it makes absolutely sense to access Shared members via an instance.

Option Strict Off(松散输入)一起使用时也有意义:在这里,您有时不知道变量的类型,但您仍然可能想要访问 Shared 成员.现在,您别无选择,只能使用实例来访问它:

It also makes sense when used together with Option Strict Off (loose typing): here, you sometimes don’t know a variable’s type but you still might want to access a Shared member. Now, you’ve got no choice but to use an instance to access it:

Option Strict Off
' … '
Dim o As Object = New A()
' Somewhere else, we want to access a static member of A but we don’t know A: '
Dim instance = o.Instance

这篇关于VB.NET 中的静态/共享和 C# 可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆