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 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]nullを返します...

于 2012-06-13T21:15:38.413 に答える
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 に答える