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

查看:68
本文介绍了为什么我不能宣布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差那么多()。加分的人,可以指出一些语言支持虚拟静态方法。

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.

编辑:确定是的,我疯了。谷歌搜索结果让我想我是不是有点那里。

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

推荐答案

虚拟静态方法没有意义。如果我称之为 HelperClass.HelperMethod(); ,为什么我会想到叫一些随机的子类'的方法?该解决方案真的坏了,当你有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天全站免登陆