--- lang: ja-jp breaks: true --- # C# ジェネリックメソッドをリフレクションにより実行する 2021-09-26 ## 静的ジェネリックメソッドを実行する ```csharp= public class RandomValueCreator { public static object GetRandomValue( Type type ) { object ret = null; ・・・ return object; } public static object Invoke_GetRandomValue_Queue(Type type) { MethodInfo method = typeof(RandomValueCreator).GetMethod( nameof(GetRandomValue_Queue), genericParameterCount : 1, // 型パラメータが1つのジェネリックメソッド types : new[] { // メソッドのパラメータの型を指定する typeof(Type) } ); MethodInfo methodGeneric = method.MakeGenericMethod(type); var ret = methodGeneric.Invoke(null, new object[] { type }); return ret; } public static Queue<T> GetRandomValue_Queue<T>(Type type) { Queue<T> ret = new Queue<T>(); for (int i = 0; i < 10; i++) { T value = (T)GetRandomValue(type); ret.Enqueue(value); } return ret; } ``` ###### tags: `C#` `ジェネリックメソッド` `リフレクション`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up