MustInherit 和共享函数
我正在查看一个 VB.NET 类(我没有编写),该类被声明为 MustInherit
(我相信是 C# 中的 abstract
),它具有三个方法,全部其中定义为 Shared
(C# 中的static
)。 该类中没有属性或字段 - 只有三个方法。 从面向对象的角度来看,这有意义吗?
我的想法是否定的,因为通过将其设置为 MustInherit
,您实际上是在说您无法创建此类的实例 - 您必须从它继承并创建派生<的实例/em> 类。 但由于所有方法都是共享的,因此您永远不会真正创建父类的实例,因此 MustInherit
没有任何好处。 您不妨不将其标记为MustInherit
,并在需要时继承它。
在某种情况下,以这种方式创建一个类是否有意义?
I'm looking at a VB.NET class (that I didn't write) that is declared MustInherit
(abstract
in C#, I believe) that has three methods, all of which are defined as Shared
(static
in C#). There are no properties or fields in the class - only the three methods. From an OO perspective, does this make any sense?
My thinking is no, because by making it MustInherit
, you're essentially saying you can't create an instance of this class - you must inherit from it and create an instance of the derived class. But since all the methods are shared, you'll never actually create an instance of the parent class anyway, so the MustInherit
does no good. You might as well not mark it MustInherit
and just inherit from it whenever you want.
Is there a situation where creating a class this way makes sense?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从面向对象的角度来看,这没有多大意义。
但是,VB 无法像 C# 那样将类标记为 Shared。 在 C# 中,您可能会将此类标记为
静态类
- 添加 MustInherit 很可能是为了阻止人们创建它的实例,即使它基本上是一个静态类。From an OO perspective, this doesn't make a lot of sense.
However, VB doesn't have a way to flag a class as Shared, like C# does. In C#, you'd likely flag this class as a
static class
- the MustInherit was most likely added to try to prevent people from creating an instance of it, even though it's basically a static class.在 C# 中,一个类可以声明为静态(= Shared),我认为 VB.NET 不允许这样做,因此作为一种解决方法,它被标记为抽象(MustInherit),以便它永远不会被实例化
In C# a class can be declared as static (= Shared), and I think VB.NET doesn't allow that, so as a workaround it is marked abstract (MustInherit) so that it's never instantiated
正如其他人所说,听起来他们真的想要一个 C# 静态类。 VB 中相当于“静态”的是“共享”,但不能在 VB 中将类标记为“共享”。 不同之处在于,有人可以继承此类,然后创建一个实例。 C# 静态类是密封的。
他们应该做的是使用
模块
。 VBModule
和 C# 静态类实际上是相同的:成员与类型而不是实例关联,并且您不能从它们继承。As others have said, it sounds like they really wanted a C# static class. VB's equivalent to "static" is "shared", but you can't mark classes "shared" in VB. The difference is that someone could inherit from this class and then create an instance. C# static classes are sealed.
What they should have done is use a
Module
. A VBModule
and C# static class are virtually identical: members are associated with the type rather than an instance and you cannot inherit from them.