--- lang: ja-jp breaks: true --- # C# `Func`デリゲート型を動的に生成する方法 2021-10-31 ## 力技による生成 ```csharp= public class DynamicFunc { static ExpressionMethodCache<DynamicFunc> s_methodCache; static DynamicFunc() { s_methodCache = new(); } private static Func<TResult> Create<TResult>() { return new Func<TResult>(() => default(TResult)); } private static Func<T1, TResult> Create<T1, TResult>() { return new Func<T1, TResult>((t1) => default(TResult)); } private static Func<T1, T2, TResult> Create<T1, T2, TResult>() { return new Func<T1, T2, TResult>((t1, t2) => default(TResult)); } private static Func<T1, T2, T3, TResult> Create<T1, T2, T3, TResult>() { return new Func<T1, T2, T3, TResult>((t1, t2, t3) => default(TResult)); } private static Func<T1, T2, T3, T4, TResult> Create<T1, T2, T3, T4, TResult>() { return new Func<T1, T2, T3, T4, TResult>((t1, t2, t3, t4) => default(TResult)); } private static Func<T1, T2, T3, T4, T5, TResult> Create<T1, T2, T3, T4, T5, TResult>() { return new Func<T1, T2, T3, T4, T5, TResult>((t1, t2, t3, t4, t5) => default(TResult)); } private static Func<T1, T2, T3, T4, T5, T6, TResult> Create<T1, T2, T3, T4, T5, T6, TResult>() { return new Func<T1, T2, T3, T4, T5, T6, TResult>((t1, t2, t3, t4, t5, t6) => default(TResult)); } private static Func<T1, T2, T3, T4, T5, T6, T7, TResult> Create<T1, T2, T3, T4, T5, T6, T7, TResult>() { return new Func<T1, T2, T3, T4, T5, T6, T7, TResult>((t1, t2, t3, t4, t5, t6, t7) => default(TResult)); } private static Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> Create<T1, T2, T3, T4, T5, T6, T7, T8, TResult>() { return new Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>((t1, t2, t3, t4, t5, t6, t7, t8) => default(TResult)); } private static Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> Create<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>() { return new Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>((t1, t2, t3, t4, t5, t6, t7, t8, t9) => default(TResult)); } public static object Create(Type[] types, Type result) { Type[] genericTypeArguments = null; if (types != null) { genericTypeArguments = types.Concat(new Type[] { result }).ToArray(); } else if (result != null) { genericTypeArguments = new Type[] { result }; } else { throw new ArgumentException($"The parameter to generate the {nameof(Func<object>)} delegate has not been specified."); } Type[] parameters = null; string methodName = nameof(Create); // キャッシュ機構を備えた、式木による生成。 Delegate func = s_methodCache.GetMethod_Static( genericTypeArguments, parameters, methodName ); return func.DynamicInvoke(); } } ``` ###### tags: `C#` `Func` `リフレクション` `式木` `動的生成`