简体   繁体   English

类在C#中将接口实现为方法返回类型

[英]Class implementing interface as method return type in C#

Is it possible in C# to define return type of a method as some class that additionally implement some interface? 在C#中是否可以将方法的返回类型定义为另外实现某些接口的某些类?

For example, in GTK# application I would like to have a widget to display documents. 例如,在GTK#应用程序中,我希望有一个小部件来显示文档。 I would like to provide several implementations of that widget - one based on Gecko, one on Webkit and one, basic,on regular Gtk.TextView. 我想提供该小部件的几种实现-一种基于Gecko,一种基于Webkit,另一种基于常规Gtk.TextView。 Clearly, all those classes have to inherit from Gtk.Widget (indirectly). 显然,所有这些类都必须继承自Gtk.Widget(间接)。 I would declare an interface that all those widgets would implement. 我将声明所有这些小部件都将实现的接口。 Last, I would create a factory method that would create appropriate widget, based on eg. 最后,我将基于示例创建一个工厂方法,该方法将创建适当的小部件。 available libraries. 可用的库。 What type should factory method return? 工厂方法应返回哪种类型?

interface IDocumentView {...};

class GeckoDocumentView : Gecko.Webcontrol, IDocumentView {...};

class WebKitDocumentView : WebKit.WebView, IDocumentView {...};

class BasicDocumentView : Gtk.TextView, IDocumentView {...};

class DocumentViewFactory {
    static IDocumentView CreateView () {...};
}

What should be return type of DocumentViewFactory.CreateView method? DocumentViewFactory.CreateView方法的返回类型应该是什么? If it's not possible to specify both Gtk.Widget and IDocumentView, should it be: 如果无法同时指定Gtk.Widget和IDocumentView,则应为:

  • Gtk.Widget (base class), which will be later casted to IDocumentView? Gtk.Widget(基类),稍后将其转换为IDocumentView吗?
  • IDocumentView (interface), which will be later casted to Gtk.Widget? IDocumentView(接口),稍后将其转换为Gtk.Widget?

EDIT - can interface force inheriting from specific base class? 编辑 -接口可以强制从特定的基类继承吗?

I like to keep platform code (which GTK# falls under) out of my code as much as possible. 我喜欢尽量避免将平台代码 (属于GTK#)保留在我的代码之外

Given that, I would prefer to return IDocumentView . 鉴于此,我宁愿返回IDocumentView

This way, your code will use the IDocumentView interface and your platform plumbing code can use the Gtk.* classes. 这样,您的代码将使用IDocumentView接口,而您的平台管道代码可以使用Gtk.*类。

尝试使用抽象工厂模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM