为什么我不能声明 C# 方法虚拟和静态? [英] Why can't I declare C# methods virtual and static?

查看:26
本文介绍了为什么我不能声明 C# 方法虚拟和静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个辅助类,它只是一堆静态方法,并且想要子类化辅助类.根据子类的不同,某些行为是独一无二的,因此我想从基类调用虚拟方法,但由于所有方法都是静态的,因此我无法创建普通的虚拟方法(需要对象引用才能访问虚拟方法).

I have a helper class that is just a bunch of static methods and would like to subclass the helper class. Some behavior is unique depending on the subclass so I would like to call a virtual method from the base class, but since all the methods are static I can't create a plain virtual method (need object reference in order to access virtual method).

有什么办法可以解决这个问题吗?我想我可以使用单例..HelperClass.Instance.HelperMethod() 并不比HelperClass.HelperMethod() 差多少.Brownie 指出任何可以指出一些支持虚拟静态方法的语言的人.

Is there any way around this? I guess I could use a singleton.. HelperClass.Instance.HelperMethod() isn't so much worse than HelperClass.HelperMethod(). Brownie points for anyone that can point out some languages that support virtual static methods.

好吧,我疯了.Google 搜索结果让我觉得我不在那里.

OK yeah I'm crazy. Google search results had me thinking I wasn't for a bit there.

推荐答案

虚拟静态方法没有意义.如果我调用 HelperClass.HelperMethod();,为什么我会期望调用一些随机子类的方法?当您有 HelperClass 的 2 个子类时,解决方案真的会崩溃——您会使用哪一个?

Virtual static methods don't make sense. If I call HelperClass.HelperMethod();, why would I expect some random subclass' method to be called? The solution really breaks down when you have 2 subclasses of HelperClass - which one would you use?

如果您想拥有可覆盖的静态类型方法,您可能应该使用:

If you want to have overrideable static-type methods you should probably go with:

  • 单例,如果您希望全局使用相同的子类.
  • 如果您希望应用程序的不同部分具有不同的行为,则可以使用带有工厂或依赖项注入的传统类层次结构.

选择最适合您情况的解决方案.

Choose whichever solution makes more sense in your situation.

这篇关于为什么我不能声明 C# 方法虚拟和静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆