部分隐藏外部程序集的接口方法
我正在寻找将一个接口中的方法“发布”到另一个接口的方法,但对其他人隐藏它。
我有以下接口
public interface IFirst
{
void Forbidden();
}
public interface ISecond
{
void Test(IFirst first);
}
internal class Second : ISecond
{
void Test(IFirst first)
{
first.Forbidden();
}
}
如您所见,ISecond 的实现需要调用 IFirst 上的“Forbidden”方法。但是,我不想允许另一个程序集中的类在 IFirst 的实现上调用“Forbidden”。我可以做什么来向外界隐藏此方法,但仍允许 ISecond 的实现使用它?
I'm looking for ways to 'publish' a method in one interface to another interface, but hide it for others.
I have the following interfaces
public interface IFirst
{
void Forbidden();
}
public interface ISecond
{
void Test(IFirst first);
}
internal class Second : ISecond
{
void Test(IFirst first)
{
first.Forbidden();
}
}
As you can see, implementations of ISecond need to call method 'Forbidden' on IFirst. However, I do not want to allow classes in another assembly to call 'Forbidden' on implementations of IFirst. What can I do to hide this method from the outside world but still allowing implementations of ISecond to use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
Forbidden
方法放入另一个非公共接口中:Put the
Forbidden
method in another, non-public interface:查看内部关键字和 内部可见属性。将这些结合起来,你应该能够做你想做的事。请注意:这适用于程序集的所有内部。
have a look at the internal keyword and the internalsvisibleto attribute. with those combined you should be able to do what you want. mind you: this applies to all internals of your assembly.
我认为如果您想要接口,您对此无能为力,就好像您希望
ISecond
的公共方法接受IFirst
的参数,然后< code>IFirst 必须是公共的,其所有方法也必须是公共的,以便IFirst
的用户始终可以调用这些方法。您可以测试
IFirst
的实现,看看它是否实现了另一个内部接口,但除非您能够控制分发正在传递的IFirst
的实现这不能保证工作(即使您可以控制分发实例,也不能保证工作),因为有人总是可以传入一些不实现内部接口的其他实现。您也许可以通过使用抽象基类来做到这一点,但我还没有对此进行测试,只是一个想法:
I don't think there is anything you can do about this if you want to interfaces, as if you want a public method of
ISecond
to take a parameter ofIFirst
thenIFirst
must be public and so must all its methods, so users ofIFirst
could always call the methods.You could test the implementation of
IFirst
you are given to see if it implements another internal interface, but unless you are in control of dishing out the implementations ofIFirst
that are being passed in this is not guaranteed to work (and is not guaranteed to work even if you are in control of dishing out the instances) as someone could always pass in some other implementation which doesn't implement the internal interface.You might be able to do it by using an abstract base class instead, but I haven't tested this, just an idea: