In your scenario, you want to iterate through a collection of interfaces in a specific namespace and dynamically invoke a generic method for each interface. However, you encounter compile-time errors due to the unknown type arguments at compile time.
To dynamically call generic methods with runtime-known type arguments, you can use reflection as follows:
using System; using System.Linq; using System.Reflection; public class TestClass { public static void CallGeneric() { Console.WriteLine($"Generic type: {typeof(T)}"); } public static void Main() { var assembly = Assembly.GetExecutingAssembly(); var interfaces = assembly.GetTypes() .Where(t => t.Namespace == "MyNamespace.Interfaces"); var genericMethod = typeof(TestClass).GetMethod("CallGeneric"); foreach (var interfaceType in interfaces) { var genericMethodInstance = genericMethod.MakeGenericMethod(interfaceType); genericMethodInstance.Invoke(null, null); // No target or arguments needed } } }
In this example:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3