重写静态类的最佳实践
由于不可能在 C# 中重写静态类,因此如果我想重写一个方法,我通常会定义一个与静态方法的签名匹配的委托,然后按照以下方式修改该方法:
public static void foo(int bar)
{
if (delegatename!=null)
{
delegatename.Invoke(bar);
}
else
{
//execute previous code as normal
}
}
我感到一阵内疚,知道这有点乱。
任何人都可以建议一个更简洁的解决方案来解决这个问题(除了重写原始结构)
As it is not possible to override a static class in c#, if i want to override a method I generally define a delegate matching the signature of the static method, then modify the method along the lines of:
public static void foo(int bar)
{
if (delegatename!=null)
{
delegatename.Invoke(bar);
}
else
{
//execute previous code as normal
}
}
I feel a twinge of guilt, knowing this is a bit messy.
Can anyone suggest a neater solution to this problem (other than rewriting the original structure)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您似乎正在使用静态类作为为应用程序中的某些资源提供单个访问点的方式。如果是这种情况,您应该考虑使用单例设计模式的实现。这样做,您可以在非静态类上利用继承。
关于如何在 C# 上实现单例设计模式的更深入讨论可以在实现单例中找到C# 中的模式文章。
It seems that you are using the static class as a way to provide a single access point to some resource in your application. If it is the case, you should consider to use an implementation of Singleton design pattern. Doing it, you could take advantage of use inheritance on your non-static classes.
A deeper discussion on how to implement the singleton design pattern on C# can be found on Implementing the Singleton Pattern in C# article.
考虑使用依赖注入,因为静态单例使得测试隔离基本上不可能,并且重用性极其痛苦。
单例很酷,只是不要使用静态来实现。有很多关于“依赖注入”的资源,Google 可以轻松为您找到。
Consider using dependency injection, as static singletons make test isolation essentially impossible and re-usability extremely painful.
Singletons are cool, just don't do it using statics. There are many resources on "dependency injection," which Google can easily find for you.