Home >Backend Development >C++ >How to Call a Generic Method with a Runtime-Determined Type Argument?
You want to invoke a generic method with a type argument that is not known until runtime. For instance, you have a list of interfaces, and you want to call a generic method for each interface.
Since the type argument is not known at compile time, you cannot use traditional method invocation with generics. Instead, you need to use reflection to dynamically invoke the generic method based on the type argument obtained at runtime.
Here's how you can implement this approach:
// Original Method public void Method<T>() { // Method body } // Main Method var assembly = Assembly.GetExecutingAssembly(); var interfaces = assembly.GetTypes().Where(t => t.Namespace == "MyNamespace.Interfaces"); foreach (var interfaceType in interfaces) { MethodInfo genericMethod = typeof(Test).GetMethod("Method"); MethodInfo specificMethod = genericMethod.MakeGenericMethod(interfaceType); specificMethod.Invoke(null, null); // No arguments for this example }
By utilizing reflection, this approach allows you to dynamically call the generic method with unknown type arguments at runtime.
The above is the detailed content of How to Call a Generic Method with a Runtime-Determined Type Argument?. For more information, please follow other related articles on the PHP Chinese website!