Call the generic method when the type parameters are determined when running.
Many types of applications are processed before the unknown type before runtime. In this case, the use of dynamically obtained type parameters to call the generic method is very important. This article discusses the best practice to achieve this task.
Assuming the following scene: In the
method, we need to use calling the generic method Example()
in the myType
variable Type
. The method of calling GenericMethod<T>()
directly is not feasible. GenericMethod<myType>()
constructing generic method by providing appropriate type parameters. Finally, we use the calling the generic method. GetMethod()
MakeGenericMethod()
Invoke()
If the generic method is static, we pass
<code class="language-csharp">MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod)); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null);</code>
null
C# 4 introduced the "Dynamic" type inference, which simplifies this process in specific scenes. However, when type inference is not available, it is still useful to understand the reflection. Invoke
The above is the detailed content of How to Call Generic Methods with Dynamic Type Parameters in C#?. For more information, please follow other related articles on the PHP Chinese website!