投射错误(类型约束失配)

时间:2018-06-15 13:00:17

标签: f#

我有投射问题

    type IConfig = interface end

    type test(num: string) = 
        interface IConfig
        member this.num = num


    type init(context:string) = 
        interface IConfig
        member this.context = context


let dict:Dictionary<string, IConfig> = new Dictionary<string, IConfig>()
dict.Add("x1", new test() { num = "1" });
dict.Add("x2", new init() { context = "1" });

for item in dict do
    if(item.Key = "x1") then
        let x = (item.Value :> init).context 
//Here I have an error: Type constraint missmach. The type IConfig is not compatibile with type InitConfig 

我对C#做了同样的事情,但它确实有效。 请帮忙。

1 个答案:

答案 0 :(得分:3)

我必须对您的代码进行一些更改才能使其正常运行,但我认为您正在寻找:?>运算符而不是:>运算符。 :>仅进行向上转播(即init -> IConfig),而:?>进行向下转换(即IConfig -> init),这是您在此尝试做的事情。

以下是我用来运行它的代码:

open System.Collections.Generic

type IConfig = interface end

type test(num: string) = 
    interface IConfig
    member this.num = num


type init(context:string) = 
    interface IConfig
    member this.context = context


let dict:Dictionary<string, IConfig> = new Dictionary<string, IConfig>()
dict.Add("x1", new test(num = "1"))
dict.Add("x2", new init(context = "1"))

for item in dict do
    if(item.Key = "x2") then
        let x = (item.Value :?> init).context 
        printfn "%A" x