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
Release: 2025-02-03 07:52:11
Original
973 people have browsed it

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
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>()
    {
        // ...
    }
}
Copy after login
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
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
Copy after login
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 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