Home > Backend Development > C++ > How Can I Call Generic Methods with Runtime-Determined Types?

How Can I Call Generic Methods with Runtime-Determined Types?

Linda Hamilton
Release: 2024-12-30 14:53:16
Original
1019 people have browsed it

How Can I Call Generic Methods with Runtime-Determined Types?

Calling Generic Methods with Types Determined at Runtime

This issue arises when attempting to call a generic method with a type parameter unknown at compile time. Ordinary method calls rely on type safety checks performed by the compiler, but when the type is only available at runtime, alternative approaches are necessary.

Reflection-Based Solution

In the context of the code example provided:

public void Method<T>() where T : class {}
public void AnotherMethod()
{
    ...
    foreach (var interface in interfaces)
    {
        Method<interface>(); // Compile error!
    }
}
Copy after login

To bypass the compile-time type checking:

  1. Retrieve the open generic method using Type.GetMethod:

    MethodInfo method = typeof(Test).GetMethod("Method");
    Copy after login
  2. Make the method generic with MakeGenericMethod:

    MethodInfo genericMethod = method.MakeGenericMethod(interface);
    Copy after login
  3. Invoke the method with Invoke:

    genericMethod.Invoke(null, null); // No target or arguments in this case
    Copy after login

Complete Example

To clarify the process, consider this revised code sample:

using System;
using System.Linq;
using System.Reflection;

namespace Sample
{
    interface IFoo { }
    interface IBar { }

    class Program
    {
        public static void CallMe<T>()
        {
            Console.WriteLine("Type of T: {0}", typeof(T));
        }

        static void Main()
        {
            var types = typeof(Program).Assembly.GetTypes().Where(t => t.Namespace == "Sample");

            var methodInfo = typeof(Program).GetMethod("CallMe");

            foreach (var type in types)
            {
                var genericMethodInfo = methodInfo.MakeGenericMethod(type);
                genericMethodInfo.Invoke(null, null);
            }
        }
    }
}
Copy after login

In this example, the generic CallMe method is called dynamically based on the types found in the Sample namespace.

The above is the detailed content of How Can I Call Generic Methods with Runtime-Determined Types?. 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