在列表中 - 如何只在基类中调用一次方法

时间:2017-03-20 09:54:45

标签: c# oop

我想从类的列表中只调用一个方法一次,所有这些类都是从base派生的,如何只在基类中调用一次方法?

Base foo()
A foo()
Base foo()
B foo()
Base foo()
A foo()

而不是:

Base foo()
A foo()
B foo()
A foo()

我想要以下结果:

html

3 个答案:

答案 0 :(得分:2)

似乎是打破SoS的荒谬要求。要回答你的问题,你需要在基类中使用静态成员boolean,并在调用基本方法时立即对其进行标记。

public class Base
{
    // is not thread safe
    protected static bool isFooCalled;

    public virtual void foo()
    {
        if(isFooCalled)
            return;
        Debug.WriteLine("Base foo()");
        isFooCalled = true;
    }
    public static void Reset()
    {
        isFooCalled = false;
    }
}

如果您甚至不想输入方法,则必须在每个派生类中添加检查。

public class A : Base
{
    public override void foo()
    {
        if(!Base.isFooCalled)
            base.foo();
        Debug.WriteLine("A foo()");
    }
}

答案 1 :(得分:0)

在基础中添加静态标志,并调整标志

public class Base
{
    public Base()
    {
        if (_instance == null)
            _instance = this;//record the first instance
    }
    static Base _instance;
    public virtual void foo()
    {
        if (_instance == this)
            Debug.WriteLine("Base foo()");
    }
}

答案 2 :(得分:0)

如果你只想执行一次逻辑,那么在基类中添加一个静态构造函数,并将base :: foo逻辑移动到这个静态构造函数

static Base()
{
   // Move the Base::foo logic here
}

这可能不是您问题的答案,但可能符合您的要求。