Skip to main content
 首页 » 编程设计

c#之让 API 环绕接口(interface)的目的

2024年02月24日18TianFang

我正在开发一个 C# 网络应用程序,它有一个页面 (MainPage),其中有一个小区域来显示小工具。有几种实现主接口(interface) (IMainInterface) 和可选接口(interface) (IOptionalInterface) 的小工具。

在 MainPage 中,当与小工具类交互时,它使用以下语法:

MyAPI api = new MyAPI(); 
api.SomeMethod(gadgetClassName, param); 

在 api.SomeMethod(...) 中,它执行以下操作:

//  use reflection to get an IMainInterface based on gadgetClassName 
Type t = Type.GetType(gadgetClassName); 
 
IMainInterface gadget = (IMainInterface)t.InvokeMember( 
    gadgetClassName, 
    BindingFlags.CreateInstance, 
    null, 
    null, 
    null); 
return gadget.SomeMethod(param) 

看看这个 MyAPI 类,它包含一大堆方法,这些方法映射到 IMainInterface 和 IOptionalInterface 中定义的相应方法。

我的问题是,这个 MyAPI 类真的有必要吗?如果 MainPage 直接访问接口(interface)(IMainInterface 和 IOptionalInterface),是不是会减少开销?

更新:看到一些答案,我意识到我没有明确表示“几种小工具”是指不同的类(例如 CalendarGadget、TaskGadget)。

更新 2:添加了更多代码示例

请您参考如下方法:

MyApi 类看起来像是在阻止您使用反射来创建对象,null 检查可选接口(interface)是否未被使用,并且可能是一般使用接口(interface)的全部事实。没有所有代码,这是猜测。正如 Dzmitry Huba 指出的那样,混合工厂和包装器是一种难闻的气味,您应该尝试重构它。

static class GadgetFactory 
{ 
    public static IMainInterface GetGadget(string className) 
    { 
         (IMainInterface)Activator.CreateInstance(Type.GetType(className)) 
    } 
} 

工厂解耦了创建的逻辑,但它应该只负责创建。

问:myAPI 中是否有任何逻辑,或者如果小工具支持该接口(interface),它是否只是创建然后调度?

如果 MyApi 没有任何逻辑,就很难看出为什么需要它。也许 MyApi 的编写者当时没有意识到您可以在需要时转换到其他接口(interface)。我有一种预感,他们试图保护初级开发人员免受界面的影响。

// basic use of interfaces 
IMainInterface gadget = GadgetFactory.GetGadget("Gadgets.Calendar"); 
gadget.SomeMethod(); 
 
IOptionalInterface optional = gadget as IOptionalInterface; 
if( optional != null ) // if optional is null, the interface is not supported 
    optional.SomeOptionalMethod(); 

一个相关的 SO 问题 Difference between Activator.CreateInstance() and typeof(T).InvokeMember() with BindingFlags.CreateInstance