静态虚拟方法有意义的场景
我知道虚拟方法和静态方法是对立的概念,但我认为有时将它们一起使用是有意义的。关于这个主题已经有很多类似的问题了,但是下面的场景还没有被涵盖。
有一个如下所示的 C# 接口:
interface IVertexMeshLoader
{
VertexMesh LoadFromFile(string fname);
}
其实现可能如下所示:
class VertexMeshLoaderObj : IVertexMeshLoader
{
public VertexMesh LoadFromFile(string fname) { .. }
}
现在我希望能够在没有对象实例的情况下调用方法,但我无法将 LoadFromFile()
方法设置为静态,因为它实现了接口。
到目前为止,我找到的最佳解决方案是编写一个包含实际代码的静态方法 LoadFromFileStatic()
。然后,LoadFromFile()
就调用它。不太漂亮,恕我直言。
我还可以在每次想要调用该方法时创建一个 VertexMeshLoadObj 实例,但这更糟糕。
还有更好的方法吗?谢谢 :-)
I know that virtual
and static
methods are opposing concepts, but I think that it could make sense sometimes to use them together. There have been quite a bunch of similiar question on SO on this topic, but the following scenario has not been covered yet.
There's a C# interface that looks like this:
interface IVertexMeshLoader
{
VertexMesh LoadFromFile(string fname);
}
An implementation of that could look like this:
class VertexMeshLoaderObj : IVertexMeshLoader
{
public VertexMesh LoadFromFile(string fname) { .. }
}
Now I would like to be able to call method without an object instance, but I cannot make the LoadFromFile()
method static, because it implements the interface.
The best solution I worked out so far is to write a static method LoadFromFileStatic()
that contains the actual code. The LoadFromFile()
then just calls it. Not very pretty, imho.
I could also create an instance of VertexMeshLoadObj
every time I want to call the method, but that is even worse.
Are there better ways? Thanks :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是另一种选择。提供仅调用静态方法的接口的显式实现。它允许他们有相同的名字
Here's another option. Provide an explicit implementation of the interface which just calls the static method. It allows them to have the same name
如果必须这样做,请创建 IVertexMeshLoader 的单例实例并访问该实例
If you must do this, create a singleton instance of IVertexMeshLoader and access that
即使您只对对象的虚函数表感兴趣而不是实际的成员,您也需要一个对象实例来知道要调用什么方法。
因此,即使实际的实现似乎并不依赖于实例,但实际上却依赖于实例。
您使用的不是“静态虚拟”方法,而是真正的虚拟方法。
Even if you're only interested in the vtable of the object and not in the actual members, you need an object instance to know what method to call.
So even if the actual implementation doesn't seem to depend on the instance, it in fact does.
You're not using "static virtual" methods but really virtual ones.