扩展现有接口

10
我遇到了一个问题。我在程序中使用了一个提供接口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!

即使我没有访问IStreamable接口的源代码,是否有一种方法可以使用newMethod声明扩展IStreamable接口?

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

希望我的回答足够清晰明了!


为什么不能直接将对象转换为所需的类型?(或者在对象上创建和实现新接口可能更好) - Alexei Levenkov
1
如果您正在编写插件,那么“IStreamable”接口听起来像是您的插件与程序之间的契约。如果是这样,即使您公开了新方法,程序将如何调用该方法?如果我错了,并且您实际上是在对象上执行调用,那么当然没有必要扩展接口,因为您只需将对象强制转换为其实际类型并直接调用该方法即可。 - dlev
@dlev 核心程序使用IStreamable。我正在为核心程序开发一个插件,需要使用相同的IStreamable对象,但我只需要为私有属性添加额外的Getter/Setter方法(以使插件正常工作)。更具体地说,核心程序加载视频摄像头并播放/停止实时流。我的插件旨在同步两个加载的摄像头,以便拥有立体视觉设置(我需要告诉我的相机DLL它是否处于立体模式,因此需要在DLL中添加新的getter/setter方法)。 - Carlo M.
@Voreno 在这种情况下,“告知”的是谁?核心程序?您的DLL的另一部分?我想我仍然认为有趣的问题是,您是否可以让核心程序执行不属于IStreamable的方法。它提供了事件机制吗?也许? - dlev
3个回答

19

您可以使用一个扩展方法

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

8
您可以使用自定义接口继承接口:
public interface IDFKStreamable : IStreamable
{
    void NewMethod();
}

那么,任何实现自定义接口的对象也必须实现 IStreamable,你可以在代码中使用自定义接口:

public class DFKCamera : IDFKStreamable
{
    // IStreamable methods

    public void NewMethod() {}
}

// elsewhere...

IDFKStreamable DLLObject = new DFKCamera();
DLLObject.NewMethod();

由于它仍然是一个 IStreamable,您应该仍然能够在现有代码中将其用作其中之一:

someOtherObject.SomeMethodWhichNeedsAnIStreamable(DLLObject);

谢谢回复,问题是我无法修改"IStreamable DLLObject = new DFKCamera()"这行代码,因为该行代码在核心文件中,我没有修改权限。 - Carlo M.

2

当你需要使用newMethod()时,为什么不将其转换回DFKCamera,这样你就可以访问它了呢?

IStreamable DLLObject = new DFKCamera();
((DFKCamera)DLLObject).newMethod();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接