我们如何通过反射获得像
Tuple.Create
这样具有多个泛型重载的方法,并将其与我们的自定义泛型类型参数一起使用?
用例:泛型类型参数仅在运行时已知。
技巧是我们应该使用
GetMember()
而不是 GetMethod()
。
我们还应该将 MemberInfo
转换为 MethodInfo
以便调用找到的方法。
答案如下:
// step 1. get Tuple.Create member
var createMembers = typeof(Tuple).GetMember("Create", BindingFlags.Static | BindingFlags.Public);
// step 2. find desired overload.
// here we find an overload that has two parameters.
var createMethodGeneric = (MethodInfo)createMembers.FirstOrDefault(m => ((MethodInfo)m).GetParameters().Length == 2);
// step 3. create a closed-generic method out of the open-generic method definition
var createMethod = createMethodGeneric.MakeGenericMethod(new[] { typeof(int), typeof(string) });
// step 4. now the createMethod can be called
// here, we pass null to the first parameter in Invoke(), since our method is static.
var myTuple = createMethod.Invoke(null, new object[] { 10, "red" });
// this is equal to the following code:
// myTuple = Tuple.Create<int, string>(10, "red");