扩展现有界面

Vor*_*eno 8 c# dll interface

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

然后我在我创建的DLL中实现接口,DFKCamera类.

在我当前的程序中(遗憾的是我无法完全修改因为我只是为它编写插件)然后我只能访问在IStreamable接口中定义的DFKCamera方法.但是,我需要访问我在DFKCamera中编写的另一种方法,以便我的插件工作(程序的其余部分不使用的方法,因此在IStreamable中没有定义).

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

就是这样的情况:

//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!
Run Code Online (Sandbox Code Playgroud)

有没有办法使用newMethod声明扩展IStreamamble接口,即使我无法访问IStreamable接口的源代码?

我知道可以使用部分接口定义来定义跨文件的接口,但是只有在两个文件中使用partial关键字并且如果在单个.DLL中编译它们时才有效.

我希望这很清楚!

And*_*ker 13

您可以使用扩展方法:

public static class IStreamableExtensions
{
    public static void NewMethod(this IStreamable streamable)
    {
        // Do something with streamable.
    }
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*vid 7

您可以使用自定义界面从界面继承:

public interface IDFKStreamable : IStreamable
{
    void NewMethod();
}
Run Code Online (Sandbox Code Playgroud)

然后,任何实现自定义接口的对象也必须实现IStreamable,您只需在代码中使用自定义接口:

public class DFKCamera : IDFKStreamable
{
    // IStreamable methods

    public void NewMethod() {}
}

// elsewhere...

IDFKStreamable DLLObject = new DFKCamera();
DLLObject.NewMethod();
Run Code Online (Sandbox Code Playgroud)

因为它仍然是一个IStreamable你仍然可以在现有代码中使用它作为一个:

someOtherObject.SomeMethodWhichNeedsAnIStreamable(DLLObject);
Run Code Online (Sandbox Code Playgroud)