0

我正在处理一些现有的代码。几个小时后,我把这个问题归结为一个方法选择器类。我觉得这门课很难学。是否有可能以简单的方式实现这种类型的方法选择功能?

public class MethodPicker
    {
        private delegate string SomeFunc(MethodPicker item);

        static readonly Dictionary<string, SomeFunc> test = new Dictionary<string, SomeFunc>();

        static MethodPicker()
        {
            test.Add("key1", Func1);
            test.Add("key2", Func2);
            test.Add("key3", Func3);
        }

        public string RunTest(string Name)
        {
            string somestring = test[Name].Invoke(this);
            return somestring;
        }

        public static string Func1(MethodPicker entity)
        {
            return "func1 runs";
        }

        public static string Func2(MethodPicker entity)
        {
            return "func2 runs";
        }

        public static string Func3(MethodPicker entity)
        {
            return "func3 runs";
        }
    }
4

2 回答 2

0

我决定用一个新属性和一个扩展方法来隐藏复杂性。

public class MethodPicker 
    { 
        public string Name {get;set;}
    } 

public static class Extensions
{     
        private delegate string SomeFunc(MethodPicker item); 
        static readonly Dictionary<string, SomeFunc> test = new Dictionary<string, SomeFunc>(); 

        static Extensions() 
        { 
            test.Add("key1", Func1); 
            test.Add("key2", Func2); 
            test.Add("key3", Func3); 
        } 

        public string AsSpecialString(this MethodPicker obj) 
        { 
            string somestring = test[obj.Name].Invoke(obj); 
            return somestring; 
        } 

        string Func1(MethodPicker entity) 
        { 
            return "func1 runs"; 
        } 

        static string Func2(MethodPicker entity) 
        { 
            return "func2 runs"; 
        } 

        static string Func3(MethodPicker entity) 
        { 
            return "func3 runs"; 
        } 
}
于 2012-06-13T21:25:00.160 回答
0

那么这将是一个更简单的解决方案..

public class MethodPicker
    {
        public string RunTest(string Name)
        {
           string somestring;
           if (Name.equals("key1") 
              return Func1(this);
           else if(Name.equals("key2") 
               return Func2(this);
           else if (Name.equals("key3") 
               return Func3(this);
           else 
              throw new Exception(name + " not found.. ");
        }

        public static string Func1(MethodPicker entity)
        {
            return "func1 runs";
        }

        public static string Func2(MethodPicker entity)
        {
            return "func2 runs";
        }

        public static string Func3(MethodPicker entity)
        {
            return "func3 runs";
        }
    }

它还强调了字典解决方案中的潜在问题,因为如果字典中不存在键/名称,则您没有适当的错误处理。在您的解决方案中,它会在此处导致 NullPointerException:

string somestring = test[Name].Invoke(this);

test[Name]将返回空...

于 2012-06-13T21:15:38.413 回答