C#有没有办法从dll实现类的接口?

时间:2017-11-03 12:04:04

标签: c# dll interface tdd

我使用了很多课程的dll。我想为这些类实现dinamically接口,然后我可以通过mock对它们进行单元测试。

有办法吗?

示例:

dll有一个Comunicator类

public class Comunicator
{
    public void Execute()
    {
        //execute something
    }
}

有没有办法让这个类在dinamically下面实现接口?

public interface IComunicator
{
    void Execute();
}

这样我想要下面的属性

public IComunicator Comunicator{ get; set; }

能够理解这项任务

Comunicator = new Comunicator();

1 个答案:

答案 0 :(得分:1)

  

有没有办法让这个类动态地实现以下接口?

简答:

如果dll是第三方库,那么您无法修改该类,因为您无法控制它。

然而,您可以创建自己的类和抽象来封装第三方依赖项。

您可以创建所需的界面

public interface IComunicator {
    void Execute();
}

使用封装

public class MyCommunicator : ICommunicator {
    private readonly Communicator communicator = new communicator();

    public void Execute() {
        communicator.Execute();
    }
}

或继承(如果类没有密封

public class MyCommunicator : Communicator, ICommunicator {

}

这样下面的属性

public IComunicator Comunicator{ get; set; }

将能够理解这项任务

obj.Comunicator = new MyComunicator();
相关问题