Home > Backend Development > C++ > How to Call Generic Methods with Dynamic Type Parameters in C#?

How to Call Generic Methods with Dynamic Type Parameters in C#?

Mary-Kate Olsen
Release: 2025-02-03 07:55:09
Original
635 people have browsed it

How to Call Generic Methods with Dynamic Type Parameters in C#?

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>()

In order to call the generic method with dynamic type parameters, we use reflection. First, we use the acquisition method metadata. Then, we use the

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

as the first parameter to
<code class="language-csharp">MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);</code>
Copy after login
. This step has nothing to do with generic methods, which is a general reflection practice.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template