如何强制抽象类的孩子实现静态方法? [英] How to force abstract class childs to implement a static method?

查看:88
本文介绍了如何强制抽象类的孩子实现静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何强制继承类在C#中实现静态方法?

Possible Duplicate:
How can I force inheriting classes to implement a static method in C#?

我理解抽象和静态是相反的,但是我想强制派生类实现静态方法.我该怎么办?

I understand abstract and static are opposite, but I want to force derived classes to implement a static method. how can I do that?

在SimonC之后 在尝试描述我想做的事情时,我意识到超类的静态方法将无法调用重写的子类版本.

Edit after SimonC : While trying to describe what I want to do, i realized that static methods of super class will not be able to call the overridden subclass version.

但是olivier的替代解决方案看起来不错.

But olivier's alternative solution looks nice.

推荐答案

将静态行为与继承或接口实现相结合的一种可行方法是使用单例模式.对单例对象的访问是静态的,但该对象是使用new创建的,就像普通"对象

A possible approach of combining a static behavior with inheritance or interface implementation is to use the singleton pattern. The access to a singleton object is static, but the object is created with new like a "normal" object

public interface ISomeInterface { ... }

public class SomeClass : ISomeInterface
{ 
    public static readonly SomeClass Instance = new SomeClass();

    private SomeClass()
    { 
    }

    // Implement ISomeInterface
    // or override an abstract member from a base class (not shown here).
}


访问单例方法


Accessing a method of the singleton

ISomeInterface obj = SomeClass.Instance; // Static access to interface.
var y = obj.SomeMethod(x);

这篇关于如何强制抽象类的孩子实现静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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