Implications of “Public Shared” Sub / Function in VB

百般思念 提交于 2019-12-08 18:43:39

问题


Can anyone explain me in VB i need to use Public Shared Sub so it can be accessed from another form.

But what this "Public" and "Shared" means?

  • Who is public?
  • With who is shared?

If it is public shared does this means some other software or "some hacker app" can easier have access to this sub and it's values?


回答1:


In VB.NET, Shared is equivalent to static in C# - meaning the member belongs to the class, not an instance of it. You might think that this member is 'Shared' among all instances, but this is not technically correct, even though VB.NET will resolve a Shared member though an instance invocation.

public class1
    public shared something as string
    public somethingelse as string
end class

The following code illustrates how VB.Net allows you to access these:

...
class1.something = "something" 'belongs to the class, no instance needed

dim x as new class1() with {.somethingelse = "something else"}

Console.WriteLine(x.somethingelse) 'prints "something else"

Console.Writeline(class1.something) 'prints "something" <- this is the correct way to access it

Console.Writeline(x.something) 'prints "something" but this is not recommended!
...

Public means any linking assembly can see and use this member.




回答2:


The Public accessor keyword simply means that the method, property, etc. is visible and callable from outside of the DLL or Assembly that defined it.

The Shared keyword means that the method, etc. is not "instanced". That is, it is part of the Class definition only, and not part of the objects that are created ("instanced") from that Class definition. This has two principal effects:

  1. The Shared method can be called at anytime, without actually having an object/instance of that Class. and,
  2. Shared methods cannot access any of the non-Shared parts of the Class definition (unless an object instance is passed to it). They can only directly access the other Shared parts of the Class definition.


来源:https://stackoverflow.com/questions/12991620/implications-of-public-shared-sub-function-in-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!