Home > Backend Development > C++ > How to Use Reflection to Invoke Generic Methods with Dynamic Type Parameters?

How to Use Reflection to Invoke Generic Methods with Dynamic Type Parameters?

DDD
Release: 2025-02-03 07:57:13
Original
285 people have browsed it

How to Use Reflection to Invoke Generic Methods with Dynamic Type Parameters?

Using reflex dynamic calling the generic method

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.

    Methodinfo using reflex retrieval instance method.
  1. Use the type parameters specified by the MakeGegnericMethod to construct the generic method.
  2. Use Invoke to call the generic method on the instance.
  3. Call the static generic method
Type myType = FindType(typeName);
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
Copy after login

Methodinfo using the static method of reflection construct.

Use the type parameters specified by the MakeGegnericMethod to construct the generic method.
  1. Use Invoke to call the static generic method.
  2. Please note that for the static method, the null is passed to Invoke as the first parameter.
<注意> Other precautions
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.StaticMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(null, null);
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template