两个项目之间的接口实现

时间:2014-01-17 19:07:14

标签: c# vb.net interface circular-reference

从搜索解决方案到两个项目之间的循环引用问题,我遇到了这个:

You can have A depend on B. For simplicity lets say A.EXE depends on B.DLL. Then when A initially calls B, it can give it an object of some type or interface that is defined in B and then B can turn around and call back into A at some later point.

In other words, B defines a base class or interface like "I want something that only A can do" but don't implement it. Then let A implements it, passes it to you, and calls it. This gets around the circular dependency without a third project. This applies to any pair of managed projects.

我尝试实现所说的内容,但我似乎没有做对。所以我的问题是,有人能为我提供一个如何实现这个的代码示例(最好是VB.Net,C#会做什么)?

供参考,原始问题在这里: Solving circular project dependency between C# and C++/CLI projects?

1 个答案:

答案 0 :(得分:2)

只是一个小小的挑剔。这不是一个真正的循环依赖,因为“这只是A可以做的事情”的想法是错误的。所有B 确实都知道“这是其他人只能做的事情”。可能只有A可以执行此操作,但B无法知道。

无论如何,一个简单的例子是:

在汇编B中:

public interface ISomething
{
    void PerformAction();
}

public class ActionManager
{
    public void DoSomething(ISomething something)
    {
        something.PerformAction();
    }
}

汇编A(引用B):

public class ActionPerformer : ISomething
{
    public void PerformAction()
    {
        ...
    }
}

public class Program
{
    public static void Main()
    {
        ActionManager manager = new ActionManager();
        ActionPerformer performer = new ActionPerformer();

        manager.DoSomething(performer);
    }
}

简而言之,此示例演示的代码(在完全多态解析后)A调用B,然后B调回A