When using generic methods in C#, sometimes the type parameters are unknown when compiling, and must be obtained at runtime. This article discusses the best practice of calling the generic method in this case.
Consider the following code examples, where
Methods try to use the type parameters obtained from runtime variables to call the generic method Example
. myType
GenericMethod<T>
public class Sample { public void Example(string typeName) { Type myType = FindType(typeName); GenericMethod<myType>(); // 这行代码无法编译通过 StaticMethod<myType>(); // 这行代码也无法编译通过 } public void GenericMethod<T>() { // ... } public static void StaticMethod<T>() { // ... } }
GenericMethod<myType>
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod)); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null);
GetMethod
For static methods, MakeGenericMethod
passed Invoke
as the first parameter to
null
In C# 4 and higher versions, if type inference is possible, dynamic calls can be used to further simplify this process, but this is not always the case. The solution provided by reflection is still a reliable method for calling the generic method using dynamic type parameters. Invoke
The above is the detailed content of How Can I Invoke Generic Methods in C# with Dynamic Type Parameters at Runtime?. For more information, please follow other related articles on the PHP Chinese website!