【问题标题】:C# Is there a way of implementing interfaces for classes from dlls?C# 有没有办法为 dll 中的类实现接口?
【发布时间】:2017-11-03 12:04:03
【问题描述】:

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

有办法吗?

例子:

dll有一个类Communicator

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

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

public interface IComunicator
{
    void Execute();
}

这样我想要下面的属性

public IComunicator Comunicator{ get; set; }

能够理解这个作业

Comunicator = new Comunicator();

【问题讨论】:

  • 这个问题不清楚。
  • 当您尝试从 dll 实现接口时发生了什么?你有吗?
  • 对不起,我现在对我的问题做了更好的解释

标签: c# dll interface tdd


【解决方案1】:

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

简短回答:

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

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

你创建你想要的界面

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();

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多