Home >Backend Development >C++ >How Can I Invoke Generic Methods in C# with Dynamic Type Parameters at Runtime?
C#Run the dynamic type parameter of the generic scrang method
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>
<code class="language-csharp">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>() { // ... } }</code>directly, because the compiler cannot infer the type parameter during compilation. To solve this problem, we need to use reflection to obtain methods, and then use the required type parameters to "construct" it.
GenericMethod<myType>
<code class="language-csharp">MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod)); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null);</code>use the specified type parameter to construct the generic method specification. Finally, is used to call the constructor's generic method.
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!