C#-在另一个方法内部实现抽象或接口方法

问题描述 投票:-1回答:1

我正在尝试根据切换案例在另一个方法内部实现抽象或接口方法。根据给定的索引,我想实现其他方法。

代码

public interface choices    
{    
    void Effect ();    
}

public class Imple : choices    
{    
    public void Choose(int index)    
    {    
        if(index == 1)    
        {    
            void Effect()    
            {    
            // implementation here


            }    
            else if(index == 2)
            // etc.

        }    
    }
}

可以通过重写抽象方法来完成吗?谢谢。

c# interface abstract
1个回答
0
投票

如果要根据传递给Effect的参数更改Choose实现的行为,那么您将必须使用状态字段来存储该状态并在Effect中读取它,像这样

public class Imple : choices    
{    
    private int effectNum = 1; // set the default effect here

    public void Choose(int index)    
    {    
        effectNum = index;   
    }

    public void Effect()
    {
        switch (effectNum)
        {
            case 1: // implement the different effects here
                break;
            case 2:
                break;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.