C# 多个类实现同一接口 如何无需逐个实例化调用所有类的接口方法
解决方案
核心思路是通过反射自动扫描所有实现了MyInterface接口的非抽象类,自动完成实例化后批量调用MyMethod方法,后续新增实现类时无需修改调用逻辑,新增类会自动被扫描识别。
可直接运行的完整代码
using System; using System.Linq; public interface MyInterface { void MyMethod(); } public class A:MyInterface { void MyInterface.MyMethod() { Console.WriteLine("Hello World from A"); } } public class B:MyInterface { void MyInterface.MyMethod() { Console.WriteLine("Hello World from B"); } } public class C:MyInterface { void MyInterface.MyMethod() { Console.WriteLine("Hello World from C"); } } // 后续新增的D类无需修改调用逻辑即可自动被识别 public class D:MyInterface { void MyInterface.MyMethod() { Console.WriteLine("Hello World from D"); } } public class Program { public static void Main() { // 扫描所有程序集中实现了MyInterface的非抽象、非接口类型 var implementTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(assembly => assembly.GetTypes()) .Where(type => typeof(MyInterface).IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface); // 批量创建实例并调用方法 foreach (var type in implementTypes) { MyInterface instance = (MyInterface)Activator.CreateInstance(type); instance.MyMethod(); } } }
注意事项
- 如果所有实现类都在同一个程序集内,可以指定扫描单个程序集,减少反射带来的性能开销
- 若实现类存在带参数的构造函数,可以给
Activator.CreateInstance传入对应的构造参数,也可以结合依赖注入容器实现更优雅的批量注册与解析,比如.NET 自带的DI框架支持批量扫描注册所有接口实现,直接注入IEnumerable<MyInterface>即可拿到所有实例遍历调用 - 如果
MyMethod是无状态调用,可将创建好的实例缓存到静态列表中,避免每次调用都重复实例化,适合类数量较多的场景 - 你原有代码的显式接口实现逻辑完全兼容该方案,不需要做修改
内容的提问来源于stack exchange,提问作者Selastin
相关产品推荐
相关产品推荐

