禁止实例调用共享/静态方法?
是否可以禁止类的实例调用共享/静态方法?
例如:
我想允许这样做:
ClassName.MethodOne()
但我想禁止这样做:
Dim A As New ClassName
A.MethodOne()
之所以需要这样做,是因为在这种情况下,如果实例可以调用该方法,那么在语义上会造成混乱。
Is it possible to prohibit an instance of a class from calling a shared/static method?
For example:
I want to allow this:
ClassName.MethodOne()
But I want to disallow this:
Dim A As New ClassName
A.MethodOne()
The reason this is desirable is that in this case it is semantically confusing if an instance can call the method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这在 VB.Net 中是不可能的。上面的代码将发出警告(BC42025),但会成功编译。唯一的困难选择是将警告切换为错误,这将防止出现此问题。
No this is not possible in VB.Net. The above code will emit a warning (BC42025) but will sucessfully compile. The only hard option is to switch warnings to errors and that will prevent this problem.
正如所说,这是默认的警告。但有可能将其推向错误。转到 VB.net 项目的属性,然后转到“编译”选项卡,然后转到“警告配置”。找到“实例变量访问共享成员”并将其设置为错误。现在它无法编译。
As it was said it is warning by default. But it is possible to promote it to error. Go to properties of VB.net project, then Compile tab, then Warning configurations. Find there "Instance variable accesses shared member" and set it to Error. Now it will not compile.