c# - 扩展现有接口(interface)

标签 c# dll interface

我遇到了一个问题。我在我的程序中使用了一个外部库,它提供了一个接口(interface) IStreamable(我没有这个接口(interface)的源代码)。

然后我在我创建的 DLL DFKCamera 类中实现该接口(interface)。

在我当前的程序中(不幸的是我不能完全修改,因为我只是为它写一个插件)然后我只能访问在接口(interface) IStreamable 中定义的 DFKCamera 的那些方法。但是,我需要访问我在 DFKCamera 中编写的不同方法才能使我的插件工作(程序的其余部分不使用的方法,因此未在 IStreamable 中定义)。

是否可以在 C# 中扩展接口(interface)的定义?如果我可以扩展 IStreamable 接口(interface),那么我就可以访问新方法。

照原样,情况是这样的:

//In ProgramUtils.DLL, the IStreamable interface is defined
//I have only the .DLL file available
namespace ProgramUtils {
    public interface IStreamable {
       //some methods
    }
}

//In my DFKCamera.DLL
using ProgramUtils;

class DFKCamera: IStreamable {
    //the IStreamable implementation code
    ....
    //the new method I wish to add
    public void newMethod() {}


//In the the program that uses DFKCamera.DLL plugin
//The program stores plugin Camera objects as IStreamable DLLObject;
IStreamable DLLObject = new DFKCamera();
//This means that I cannot access the new method by:
DLLObject.newMethod(); //this doesn't work!

有没有一种方法可以使用 newMethod 声明来扩展 IStreamble 接口(interface),即使我无法访问 IStreamable 接口(interface)的源代码?

我知道可以使用部分接口(interface)定义来跨文件定义接口(interface),但是只有在两个文件都使用 partial 关键字并且这些文件在单个 .DLL 中编译时才有效

我希望这已经够清楚了!

最佳答案

你可以使用 extension method :

public static class IStreamableExtensions
{
    public static void NewMethod(this IStreamable streamable)
    {
        // Do something with streamable.
    }
}

关于c# - 扩展现有接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22493716/

相关文章:

c# - 将枚举存储到数据库的平滑方法

c# - 在 Entity Framework 中按子项排序不返回排序列表

c++ - 如何处理 DLL 导出接口(interface)中的析构函数

entity-framework - 使用 Entity Framework (4.2) 实体的接口(interface)时出错

c# - 通用接口(interface)列表

c# - 用表达式定义的属性与传统方式有什么实际区别?

c# - 使用生物信息学映射 C# 对象方向

java - 可运行的 JavaCV 项目

dll - Cygwin 中的 rebaseall 是做什么的?

java - 内部类默认为 "sensible"接口(interface)?