静态/在VB.NET和C#的知名度共享 [英] static/Shared in VB.NET and C# visibility
问题描述
我也遇到这样的情况在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...
//共享成员的行为就像一个班公一个我可以重复它无限..
这是微软疏忽或VB.NET功能?
is this a Microsoft oversight or a VB.NET "feature"?
推荐答案
这不是一个疏忽,但你的VB code 将触发警告,这显然意味着:不使用这个符号。
It's not an oversight but your VB code will trigger a warning, which plainly means: do not use this notation.
在VB中,静态成员的可以的可以通过一个实例访问,因为严格来说,VB的没有静态
:VB有关键字共享
,这意味着该成员的共享的所有实例之间,相对于静态
,其中一个成员不属于的任意的实例。
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#中是共享
在VB.NET,但他们的遗产是不同的, VB的共享
只是有不同的历史,因此历史上有不同的含义。通过的这个的意义,它使绝对意义上通过一个实例访问共享
的成员。
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.
这也是情理之中的时候用选项严格关
(弱类型)一起使用:在这里,你有时的不知道的变量的类型但你仍然可能需要访问一个共享
成员。现在,你有没有选择,只能使用一个实例来访问:
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屋!