1

これは私が持ちたいものです:

static void A(string s)
{
    //Code Here...
}
static void B(string s)
{
    //Code Here...
}
static void C(string s)
{
    //Code Here...
}
static void Main(string[] args)
{
      string temp = Console.ReadLine();
      string[] s = temp.Split(' ');
      if (s[0] == "A")
          A(s[1]);
      if (s[0] == "B")
          B(s[1]);
      if (s[0] == "C")
          C(s[1]);
}

しかし、メソッドがたくさんあると、うまく機能しません...

これを行う別の方法はありますか?

4

7 に答える 7

1

Dictionaryofを使用して、Actions文字列をメソッドにマップできる場合があります。

using System;
using System.Collections.Generic;

namespace Demo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            _actions = new Dictionary<string, Action<string>>();

            _actions["A"] = A;
            _actions["B"] = B;
            _actions["C"] = C;

            string[] s = Console.ReadLine().Split(' ');

            if (!processArg(s[0], s[1]))
            {
                // Argument wasn't in the list. Do error handling.
            }
        }

        static bool processArg(string name, string value)
        {
            Action<string> action;

            if (_actions.TryGetValue(name, out action))
            {
                action(value);
                return true;
            }

            return false;
        }

        static void A(string s)
        {
            Console.WriteLine("A: " + s);
        }

        static void B(string s)
        {
            Console.WriteLine("B: " + s);
        }

        static void C(string s)
        {
            Console.WriteLine("C: " + s);
        }

        private static Dictionary<string, Action<string>> _actions;
    }
}
于 2013-03-23T13:07:28.503 に答える
1

このようなものを書くことができます。

private static void Main(string[] args)
    {
        InitializeFunctions();

        string temp = Console.ReadLine();
        string[] s = temp.Split(' ');

        _functions[s[0]].Invoke(s[1]);
    }

    private static void InitializeFunctions()
    {
        _functions.Add("A",A);
        _functions.Add("B",B);
        _functions.Add("C",C);
    }

    private static Dictionary<string, Func> _functions = new Dictionary<string, Func>();

    public delegate void Func(string process);

    static void A(string s)
    {
        //Code Here...
    }
    static void B(string s)
    {
        //Code Here...
    }
    static void C(string s)
    {
        //Code Here...
    }

同じ署名を持つ新しいメソッドがある場合は、それを InitializeFunctions メソッドの _functions 辞書に追加するだけです。

于 2013-03-23T13:08:58.340 に答える
0

あなたがやろうとしていることの詳細がなければ、基本的な代替案は、1つのメソッドを持ち、switchステートメントを使用することかもしれません。

static void PerformAction(string method, string cInput)
{
    switch(method)
    {
       case "A":                   
              //code
              //something with cInput
              break;
       case "B":
              //code
              break;
       //..
       default:
              //default action code                  
    }    

}

このように呼んでください

string temp = Console.ReadLine();
string[] s = temp.Split(' ');
PerformAction(s[0],s[1]);
于 2013-03-23T12:42:21.433 に答える
0

この特定の問題を処理する方法は2つあります。

  1. switchステートメントを使用する
  2. リフレクションを使用する

Switchステートメント

この場合、次のようにコードを整理します。

switch (s[0])
{
    case "A":
        A(s(1));
        break;

    case "B":
        B(s(1));
        break;

    // and so on
}

**リフレクションを使用**

文字列から名前を取得して名前でメソッドを呼び出す場合は、リフレクションを使用する必要があります。

MethodInfo method = typeof(Program).GetMethod(s(0)); // guessing "Program" here
if (method != null)
    method.Invoke(null, new object[] { s(1) });

ただし、ユーザーからの入力を使用してこれを行うことはありません。これはSQLインジェクション攻撃のようなものであり、さらに悪いことです。

于 2013-03-23T12:45:00.413 に答える
0

使いたいものはこんな感じです。

typedef void (*FuncType)();

std::map<char, FuncType> Fonctions;

Fonctions['A'] = &FonctionA;
...
Fonctions['Z'] = &FonctionZ;

Fonctions[s[0]](s[1]);

Function[s[0]]が定義されていることも確認する必要があります。

于 2013-03-23T12:40:31.590 に答える
0

これを試して:

    static void A(string s)
    {
        //Code Here...
    }
    static void B(string s)
    {
        //Code Here...
    }
    static void C(string s)
    {
        //Code Here...
    }
    public struct ActionStruct {
      public string String;
      public Action<string> Action;
      public ActionStruct(string s, Action<string> a) : this() {
        String = s; Action = a;
      }
    }
    void Main(string[] args) {
      var actions = new List<ActionStruct>() {
        new ActionStruct("A", s => A(s)),
        new ActionStruct("B", s => B(s)),
        new ActionStruct("C", s => C(s))
      };
      var action = actions.Where(a=>a.String == args[0]).FirstOrDefault();
      if (action.String!= "") action.Action(args[1]);
    }
于 2013-03-23T12:52:34.173 に答える
0

このコードは、入力が正しくないか、複数のメソッドを実行したい場合に、すべてのメソッドで機能します。

例:

コンソールから次の行を読んでいる場合

A Abcdefg

分割後、s[0] は「A」になり、s[1] は「Abcdefg」になります。

コンソールから次の行を読んでいる場合

A abcdef B bhfhhhfh C chgghh

分割後s[0]= "A", s[1]="abcdef " s[2]= "B", s[3]="bhfhhhfh " s[4]= "C", s[5]="chgghh"

この場合、s[0] と s[1] のみをチェックしているため、A(String) のみが呼び出されます。

すべてのメソッドを呼び出したい場合は、ループで実行します

for(int i=0;i<s.length;i=i+2){
  if (s[i] == "A")
          A(s[i+1]);
      if (s[i] == "B")
          B(s[i+1]);
      if (s[i] == "C")
          C(s[i+1]);
} 

編集 if を書きたくない場合は、 switch を使用できます

スイッチ (s[0]) { ケース "A": A(s(1)); 壊す; ケース "B": B(s(1)); 壊す; ケース "C": C(s(1)); 壊す; . . . . . .

}

于 2013-03-23T12:52:41.190 に答える