Using a dynamic type of type variable C#generication method
When using the generic method, you often encounter the type of parameters when compiling, but dynamically determine the type parameter during runtime. Reflex provides a powerful solution to cope with this challenge.
The solution of genetically genetically generatedhodhod
To use the type stored in Mytype variables to call the generic method genericmedhod
, you can use the following methods:
- Methodinfo using reflection method:
<code class="language-csharp">MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));</code>
Copy after login
- Provide type parameters to construct generic methods:
<code class="language-csharp">MethodInfo generic = method.MakeGenericMethod(myType);</code>
Copy after login
Copy after login
- Call the constructor's generic method:
<code class="language-csharp">generic.Invoke(this, null);</code>
Copy after login
Static method STATICMETHOD solution
To call the static generic method StaticMethod
, please follow similar steps:
- Methodinfo to get static generic methods:
<code class="language-csharp">MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.StaticMethod));</code>
Copy after login
- Use type parameter constructing generic method:
<code class="language-csharp">MethodInfo generic = method.MakeGenericMethod(myType);</code>
Copy after login
Copy after login
- Call the generic method of the constructor. Because it is a static method, the null is passed as the first parameter:
<code class="language-csharp">generic.Invoke(null, null);</code>
Copy after login
C# 4 and Dynamic keywords brought by simplified
Although the reflection provides a powerful solution for calling the generic method, it may involve quite a lot of model code. However, starting from C# 4, you can use Dynamic keywords to simplify this process. If the type inference is available, using Dynamic can significantly reduce the required code.
The above is the detailed content of How Can I Invoke Generic Methods with Dynamically Resolved Type Variables in C#?. For more information, please follow other related articles on the PHP Chinese website!