2

我有一个状态机,需要根据我所处的状态从对象列表中对每个对象调用不同的方法。基本上我正在尝试重构在我的状态机的每个案例语句中都有一个循环的代码使它看起来像下面的代码。但是我似乎无法弄清楚如何将相关方法传递给我的重构函数(更不用说我不知道​​如何在每个项目上调用它)

任何帮助,将不胜感激。

这是示例代码:

    public class MyOtherType
    {
        public bool Method1()
        { return false; }
        public bool Method2()
        { return false; }
        public bool Method3()
        { return false; }
        public bool Method4()
        { return false; }
    }

    public class MyType
    {
        public enum MyState
        {
            DoSomething1,
            DoSomething2,
            DoSomething3,
            DoSomething4
        }
        private MyState State = MyState.DoSomething1;

        List<MyOtherType> MyListOfObjects = new List<MyOtherType>() { new MyOtherType(), new MyOtherType() };

        private void StateMachine()
        {
            switch (State)
            {
                case MyState.DoSomething1:
                    //How do I pass this in? Do I need to set it up differnetly?
                    Process(() => MyOtherType.Method1());
                    break;
                case MyState.DoSomething2:
                    Process(() => MyOtherType.Method2);
                    break;
                case MyState.DoSomething3:
                    Process(() => MyOtherType.Method3);
                    break;
                case MyState.DoSomething4:
                    Process(() => MyOtherType.Method4);
                    break;
            }
        }

        private void Process(Func<bool> method)
        {
            foreach (MyOtherType item in MyListOfObjects)
            {
                //How do I call the method on each item?
                if (item.method())
                {
                    //Do something
                }
            }
        }
    }
4

2 回答 2

2

我建议摆脱这些switch块,并通过引入每个状态的灵活策略映射来将每个特定方法与状态解耦,以便可以轻松更改甚至注入:

IDictionary<MyState, Func<bool>> strategyMap;

1) 填写

 // if idea is to access methods without instance of MyOtherType - 
 // make all methods and class itself static so you can access it
 // like MyOtherType.Method1
 strategyMap = new Dictionary<MyState, Func<bool>>();
 strategyMap.Add(MyState.DoSomething1, myOtherTypeInstance.Method1);

2)调用适当的策略取决于状态而不是switch(State)

 if (starategyMap.ContainsKey(State))
 {
     // pass in an associated strategy 
     Process(starategyMap[State]);
 }

如有任何问题,请随时提问

于 2011-09-09T10:20:01.437 回答
0

一种可能的解决方案是使方法成为静态方法,并将它们应操作的类引用作为参数:

public class MyOtherType
{
    public static bool Method1(MyOtherType instance)
    { 
        return instance == null;  
    }
}
于 2011-09-09T10:26:23.933 回答