在C#中,如何使用Func <t>?</t>从另一个类传递方法

时间:2011-09-09 10:15:18

标签: c#-4.0 delegates func

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

任何帮助都将不胜感激。

以下是示例代码:

    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
                }
            }
        }
    }

2 个答案:

答案 0 :(得分: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]);
 }

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

答案 1 :(得分:0)

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

public class MyOtherType
{
    public static bool Method1(MyOtherType instance)
    { 
        return instance == null;  
    }
}
相关问题