与歧视联盟上的另一个接口的成员实现接口

时间:2019-03-21 23:16:56

标签: generics interface f# argu

我正在使用Argu解析cli参数。我注意到我需要为两个不同的事物使用相同的参数。我想使用相同的类型,只更改接口实现(我的Argument Discriminated Union上的IArgParserTemplate)。

与此类似的东西:

type IArgumentDescription =
     abstract member FirstDescription: string

type ImportArguments =
    interface IArgumentDescription with
        member this.FirstDescription = "Import Description"

type ExportArguments =
    interface IArgumentDescription with
        member this.FirstDescription = "Export Description"

type Arguments<'T when 'T :> IArgumentDescription> = | FirstArgument of string
with 
    interface IArgParserTemplate with
        member this.Usage =
            match this with
            | FirstArgument _ -> ? (Here I would like to use the 'T.FirstDescription of the IArgumentDescription Interface. (this:>IArgumentDescription).FirstDescription does not work.)

在FSharp中这是否可能,如果是,正确的语法是什么?

1 个答案:

答案 0 :(得分:1)

我想不出一个很好的方法,因为您不能真正地对一个被区分的联合进行参数化或“子类化”。您可能会使用涉及反射的肮脏技巧,但我不确定这是明智的选择(就像大多数与生产代码中反射相关的事情一样)。

type IArgParserTemplate =
    abstract member Usage : string


type IArgumentDescription =
     abstract member FirstDescription: string

// The parentheses are important to make this a class, not an interface
type ImportArguments() =
    interface IArgumentDescription with
        member this.FirstDescription = "Import Description"

// The parentheses are important to make this a class, not an interface
type ExportArguments() =
    interface IArgumentDescription with
        member this.FirstDescription = "Export Description"

type Arguments<'T when 'T :> IArgumentDescription> = | FirstArgument of string
with 
    interface IArgParserTemplate with
        member this.Usage =
            // Here's your instance of 'T
            let instance = Activator.CreateInstance<'T>()

            match this with
            | FirstArgument _ -> instance.FirstDescription