戻り値の型が違うDelegateに代入する方法。
- Func<string, int> func = Convert.ToInt32;
- Func<string, object> func2 = Delegate.CreateDelegate(typeof(Func<string, object>), func.Method) as Func<string, object>;
↑の例の場合、戻り値がintのdelegateを戻り値がobjectのdelegateとして使うことができます。
何が便利か?というと、delegateとgenericを使用して、汎用的なコンバーターが作成可能になります。
- class MyConverter<T>
- {
- private static Func<string, T> _func;
- public static T Conv(string input)
- {
- return _func(input);
- }
- static MyConverter()
- {
- MethodInfo m = null;
- Type type = typeof(T);
- if (type == typeof(int))
- {
- Func<string, int> func = Convert.ToInt32;
- m = func.Method;
- }
- else if (type == typeof(DateTime))
- {
- Func<string, DateTime> func = Convert.ToDateTime;
- m = func.Method;
- }
- _func = Delegate.CreateDelegate(typeof(Func<string, T>), m) as Func<string, T>;
- }
- }
↑のようなクラスを用意して、↓な感じで使用
- MyConverter<int>.Conv("123");
このようなクラスを、Reflectionと組み合わせると結構便利です。
0 件のコメント:
コメントを投稿