是否可以消除由于接口而产生的 DLL 依赖?
假设我的库类(在程序集 A 中)有一个方法 GetFoo()
返回类型 Foo
。 Foo
实现了多个接口,包括程序集 B 中的 IBar
。当客户端代码调用 GetFoo()
时(客户端代码不引用程序集 B) ,编译器将给出错误,因为 IBar
“是在未引用的程序集中定义的。您必须添加对程序集 B 的引用”。请注意,我的代码只需要了解 Foo,并且它不包含对该接口的引用。
是否可以不必引用 B?据我所知,运行时不需要知道它。
Let's say my library class (in assembly A) have a method GetFoo()
returns a type Foo
. Foo
implements several interfaces, including IBar
in assembly B. When a client code calls GetFoo()
(the client code does not reference assembly B), the compiler will gives an error, because IBar
"is defined in an assembly that is not referenced. You must add a reference to assembly B". Note that my code only needs to know about Foo, and it contains no reference to the interface.
Is it possible to not have to reference B? As far as I know there is no need for the runtime to know about it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
运行时需要接口,需要程序集B。
如果调用者实际上并不关心该接口,则可以选择不实现它,然后不需要程序集 b。如果有时需要,有时不需要,则可以使用
#if
指令和编译器标志来创建程序集 a 的两个版本,一种使用 b,另一种不使用。在我看来,有两个版本有点过分了。Interfaces are needed at runtime and assembly B is needed.
If the caller actually doesn't care about the interface, you can choose not to implement it and then don't need assembly b. If you sometimes need it and sometimes don't, you can use
#if
directives and compiler flags to create two versions of assembly a, one that uses b and one that doesn't. It's way overkill IMO though to have two versions.该方案适用于带有 COM 的 C++ 等本机语言,因为该接口仅指定在编译时检查但不在运行时强制执行的约定。但是,在 .NET 中,CLR 在运行时强制执行类型安全,因此它需要引用定义接口的程序集。
如果您的情况允许,您可能希望将接口分解为单独的“合同”程序集,并让两个程序集都引用它。它将是一个非常小的组件,并且加载速度应该非常快。
That scenario works in native languages like C++ with COM because the interface simply specifies a convention that is checked at compile time but not enforced at runtime. However, in .NET the CLR enforces type safety at runtime and so it needs to reference the assembly in which the interface is defined.
If your situation allows it, you may want to break out the interface into a separate "contracts" assembly and have both assemblies reference it. It will be a very small assembly and should load very quickly.
不,如果您正在处理实现某些接口的类,那么所有这些接口都应该可用于您创建或检索类的位置。
通常,这可以通过相反的方式解决,您针对接口而不是具体类进行工作,然后您只添加对接口程序集的引用,而不是对类的引用。
no, if you are dealing with classes that implement certain interfaces, all those interfaces should be available to the places where you create or retrieve the classes.
usually this is solved the other way round, you work against interfaces and not concrete classes then you only add the reference to the interface assembly and not to the classes.