- 題名: スクリプトの分岐処理の削減がしたい
- 日時: 2011/11/16 10:28:19
- ID: 29367
- この記事の返信元:
- (なし)
- この記事への返信:
- [29368] Re[1]: スクリプトの分岐処理の削減がしたい2011/11/16 10:41:44
- ツリーを表示
■No29373に返信(hiroさんの記事)
> しかし、string Function1(params string[] args)のように、stringを返す関数では、
> 「パラメータ カウンタが一致しません。」と表示され、
戻り値ではなく、パラメータが間違っているといわれていますよ。
Invoke 時の引数の渡し方にご注意ください。
(なお、out や ref の場合はまた違った呼び出し方が必要です)
class Program
{
static void Main(string[] args)
{
//MethodInfo method1 = typeof(Program).GetMethod("Func1", new Type[] { typeof(string), typeof(string) });
//MethodInfo method2 = typeof(Program).GetMethod("Func2", new Type[] { typeof(string[]) });
//MethodInfo method3 = typeof(Program).GetMethod("Func3", new Type[] { typeof(string[]) });
MethodInfo method1 = typeof(Program).GetMethod("Func1");
MethodInfo method2 = typeof(Program).GetMethod("Func2");
MethodInfo method3 = typeof(Program).GetMethod("Func3");
Console.WriteLine(method1.Invoke(null, new object[] { "aaa", "bbb" }));
Console.WriteLine(method2.Invoke(null, new object[] { new string[] { "aaa", "bbb", "ccc" } }));
Console.WriteLine(method2.Invoke(null, new object[] { new string[] { "aaa", "bbb" } }));
Console.WriteLine(method2.Invoke(null, new object[] { new string[] { "aaa" } }));
Console.WriteLine(method2.Invoke(null, new object[] { new string[] { } }));
Console.WriteLine(method2.Invoke(null, new object[] { null }));
Console.WriteLine(method3.Invoke(null, new object[] { new string[] { "aaa", "bbb", "ccc" } }));
Console.WriteLine(method3.Invoke(null, new object[] { new string[] { "aaa", "bbb" } }));
Console.WriteLine(method3.Invoke(null, new object[] { new string[] { "aaa" } }));
Console.WriteLine(method3.Invoke(null, new object[] { new string[] { } }));
Console.WriteLine(method3.Invoke(null, new object[] { null }));
Console.ReadKey();
}
public static string Func1(string a, string b)
{
return "Func1 :" + a + "," + b;
}
public static string Func2(string[] args)
{
return "Func2 :" + ((args == null) ? "null" : args.Length.ToString());
}
public static string Func3(params string[] args)
{
return "Func3 :" + ((args == null) ? "null" : args.Length.ToString());
}
}
分類:[.NET]
はじめまして、hiroです。
現在、C# でテキストファイルを読み込み、
書かれている命令によって処理を分岐するコードを書いていますが、
命令の分岐処理において、
// functionはstring。命令が入ってる
// argsはstring[]。引数が入ってる
if (function == "Function1")
{
Function1(args);
}
else if (function == "Function2")
{
Function2(args);
}
else if (function == "Function3")
{
Function3(args);
}
…
のようなコードを書いています。
functionに入ってる値と関数名は同じで、
関数側は
void Function1(params string[] args)
のようになっており、なにか無駄を感じます。
また、関数も大量に用意しているので、ifで分岐するのはかなり大変です。
このコードは省略して書く方法はありますか?
省略できるか、否か、だけでもいいので教えてください。
どなたか、回答お願いします。