定义一个继承接口的抽象类,但不实现它

时间:2010-05-22 19:50:53

标签: interface f# abstract-class

结合leppies反馈它编译 - 但IMO的一些缺点我希望编译器强制每个子类定义自己的Uri属性。代码现在是:

[<AbstractClass>] 
type UriUserControl() = 
    inherit UserControl()
    interface IUriProvider with 
        member this.Uri with get() = null

有趣的是,我从上面定义了哪些内容并没有显示公共Uri属性:

type Page2() as this =
    inherit UriUserControl()
    let uriStr = "/FSSilverlightApp;component/Page2.xaml"
    let mutable uri = new System.Uri(uriStr, System.UriKind.Relative)
    do
        Application.LoadComponent(this, uri)

    member public this.Uri with get () = uri

我想定义一个继承自UserControl和我自己的接口IUriProvider的抽象类,但是没有实现它。目标是能够定义实现UserControl的页面(用于silverlight),但也提供自己的Uri(然后将它们粘贴在列表/数组中并将它们作为一组处理:

type IUriProvider = 
interface
    abstract member uriString: String ;
    abstract member Uri : unit -> System.Uri ;
end

[<AbstractClass>] 
type UriUserControl() as this = 
    inherit IUriProvider with
        abstract member uriString: String ;
    inherit UserControl()

定义中的Uri - 我想作为属性getter实现 - 并且也遇到了问题。

这不编译

type IUriProvider = 
    interface
        abstract member uriString: String with get;
end

2 个答案:

答案 0 :(得分:8)

这是一种方法:

type IUriProvider =  
    abstract member UriString: string
    abstract member Uri : System.Uri

[<AbstractClass>]  
type UriUserControl() as this =  
    inherit System.Windows.Controls.UserControl() 
    abstract member Uri : System.Uri
    abstract member UriString : string
    interface IUriProvider with 
        member x.Uri = this.Uri
        member x.UriString = this.UriString

请注意,您必须提供接口的实现(因为F#中的所有接口实现都是显式的),但这只能引用类中的抽象成员。然后你可以这样子类:

type ConcreteUriUserControl() =
    inherit UriUserControl()
    override this.Uri = null
    override this.UriString = "foo"

答案 1 :(得分:1)

从.NET的角度来看,您至少需要为接口提供一个抽象实现。但是由于默认的接口可访问性,这再次证明是有问题的,这将需要更多的粘合剂来进行显式实现。