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

C# Is there a way of implementing interfaces for classes from dlls?

我正在使用一个包含很多 classes 的 dll。我想为这些 classes 实现动态接口,然后我可以通过模拟对它们进行单元测试。

有办法吗?

示例:

dll 有一个 class Comunicator

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

有没有办法class动态实现下面的接口?

public interface IComunicator
{
    void Execute();
}

这样我想要

下面的 属性
public IComunicator Comunicator{ get; set; }

能够理解这个作业

Comunicator = new Comunicator();

Is there a way of doing this class implementing the interface below dynamically?

简答:

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

但是您可以创建自己的 classes 和抽象来封装第 3 方依赖项。

您创建所需的界面

public interface IComunicator {
    void Execute();
}

并且要么使用封装

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

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

或继承(如果class未密封

public class MyCommunicator : Communicator, ICommunicator {

}

这边属性下面

public IComunicator Comunicator{ get; set; }

一定能看懂这个作业

obj.Comunicator = new MyComunicator();