Home >Backend Development >C++ >How Can I Invoke Generic Methods in C# with Dynamic Type Parameters at Runtime?

How Can I Invoke Generic Methods in C# with Dynamic Type Parameters at Runtime?

Susan Sarandon
Susan SarandonOriginal
2025-02-03 07:52:11903browse

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>

As shown in the example, try to call
<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>

Method to retrieve the method from the current type, and
<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

. This has nothing to do with the generic method, but only reflects the method of calling the static method through reflection.

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!

Statement:
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