Home >Backend Development >C++ >How to Use Reflection to Invoke Generic Methods with Dynamic Type Parameters?
Because the type parameters are unknown when compiling, the dynamic calling method needs to be reflected. To achieve this goal, follow the following steps:
Call the instance generic method
Get the type of scrang method declaration class.
<code class="language-csharp">Type myType = FindType(typeName); MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod)); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null);</code>
Methodinfo using the static method of reflection construct.
Use the type parameters specified by the MakeGegnericMethod to construct the generic method.<code class="language-csharp">MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.StaticMethod)); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(null, null);</code>
For C# 4 and higher versions, the use of dynamic types can simplify this process, especially when type inferring possible. However, in some types of inferences (such as the examples provided), reflexes may still be needed.
The above is the detailed content of How to Use Reflection to Invoke Generic Methods with Dynamic Type Parameters?. For more information, please follow other related articles on the PHP Chinese website!