简体   繁体   English

C# bool 并以简洁的方式关闭 function?

[英]C# bool and turn on off function with neat way?

I got following code.我得到以下代码。

public class MpChange : CusEffect
{
    bool AlreadyDo = false;
    bool AlreadyStop = false;

    public override void CondDel(object sender, CondEventArgs e)
    {
        if (e.CondMet && !AlreadyDo)
        {
            DoEffect();
            AlreadyDo = true;
            AlreadyStop = false;
        }
        else if (!e.CondMet && !AlreadyStop)
        {
            StopEffect();
            AlreadyStop = true;
            AlreadyDo = false;
        } 
    }

    public override void DoEffect()
    {
        Debug.Log(WhoEffect.name + "'s Mp changed +5");
    }
    
    public override void StopEffect()
    {
        Debug.Log(WhoEffect.name + "'s Mp changed -5");
    }
}

This is called when character's hp is full, (then DoEffect()), and if not full, then StopEffect().这在角色的 hp 已满时调用,(然后是 DoEffect()),如果未满,则调用 StopEffect()。

When character's hp is changed, event published and this MpChange class is subscribe it.当角色的 hp 改变时,事件发布并且这个 MpChange class 被订阅。

In this case, can this code be neat?在这种情况下,这段代码可以整洁吗?

I hate to using this 2 boolean variables (AlreadyDo, AlreadyStop), being confused.我讨厌使用这 2 个 boolean 变量(AlreadyDo,AlreadyStop),感到困惑。

One boolean will do:一个 boolean 可以:

    bool State = false;
    public override void CondDel(object sender, CondEventArgs e)
    {
        if (e.CondMet == State) return;  // nothing to do, state's the current one
        State = !State;  // flip the flag
        if (State) {  // do or undo a thing
            DoEffect();
        } else {
            StopEffect();
        }
    }

So instead using boolean, I should use enum.因此,我应该使用枚举而不是使用 boolean。

I set,我设置,

public enum ConditionState
{
None, Complete, Incomplete,
}

and change condition code part based on enum state and prevent duplicate calling,并根据枚举 state 更改条件代码部分并防止重复调用,

public abstract class CusCondition
{
public bool Earned;      
public int SealValueCond;
public ConditionState conditionMet;
private ConditionState prevCond = ConditionState.None;
[HideInInspector]
public Character WhoCondition;       
public virtual void ConditionEvent(object sender, MyEventArgs myEventArgs)
{
    SealManager.Instance.PublishEvent(this, new CondEventArgs(conditionMet));
}
public virtual void ConditionEventState(object sender, MyEventArgs myEventArgs)
{       // execute only once state changes 
    if (conditionMet == prevCond) return;
    prevCond = conditionMet;
    SealManager.Instance.PublishEvent(this, new CondEventArgs(conditionMet));
}
}

and then at effect part, this is enough.然后在效果部分,这就足够了。

public override void CondDel(object sender, CondEventArgs e)
{ 
    if (e.CondMet == ConditionState.Complete)
        DoEffect();
    else if(e.CondMet == ConditionState.Incomplete)
        StopEffect();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM