错误:可能需要类型注释

时间:2013-11-25 17:59:55

标签: c# f#

我想让Name返回item.name的值,其中item是C#类的一个实例。

fs文件包含

namespace PatternMatch

type PatternMatch() = 
    member this.X = "F#"

namespace Items_

fsx文件包含

#load "PatternMatch.fs"
open PatternMatch

open Items_

type item = Item

let Name item = item.name //this line throws the error

let rec sentence s item  = function
    | s when s="Action" -> ""
    | s when s="Client" -> ""
    | s when s="Classifier" -> ""    
    | s when s="Container" -> ""    
    | s when s="ControlFlow" -> ""
    | s when s="Gaurd" -> ""
    | s when s="Name" -> Name item
    | s when s="ObjectFlow" -> ""    
    | s when s="Source" -> ""    
    | _ -> ""

let Name item = item.name抛出错误。 Items_是一个C#命名空间,Item是一个C#类。

整个错误是:

  

根据此程序点之前的信息查找不确定类型的对象。在此程序点之前可能需要类型注释来约束对象的类型。这可以允许解析查找。 C:\ Users \ jzbedocs \ Local Files \ Visual Studio 2010 \ Projects \ addin \ trunk \ PatternMatch \ Script.fsx 11 17 PatternMatch

1 个答案:

答案 0 :(得分:4)

let Name item = item.name没有类型注释。除了隐式不支持的成员约束之外,参数item不受约束(参见here使其显式 - 不要这样做......)

看起来您感到困惑,因为参数名称item与类型别名item相同。如果你想明确地这样做,那就这样做:

let Name (itemParameter:item) = itemParameter.name

我没有检查参数是否可以与别名具有相同的名称,但它可能是一个坏主意,因为它可能与类型参数混淆(我们刚看到它!)。

编辑:好的,我查了一下。您可以使参数名称与参数的带注释的类型相同,但它会导致非常混乱的类型签名和实现:

> let Name (item:item) = item.name;;

val Name : item:item -> string // EW!

如果你感觉特别邪恶,你甚至可以这样做:

> let item (item:item) : item = item;;

val item : item:item -> item //Huh?

暂且不说:

let rec sentence s item  = function
    | s when s="Action" -> ""
    | s when s="Client" -> ""
    | s when s="Classifier" -> ""    
    | s when s="Container" -> ""    
    | s when s="ControlFlow" -> ""
    | s when s="Gaurd" -> ""
    | s when s="Name" -> Name item
    | s when s="ObjectFlow" -> ""    
    | s when s="Source" -> ""    
    | _ -> ""

可能更好地表达为:

let rec sentence s item  = 
    match s with
    | "Action" -> ""
    | "Client" -> ""
    | "Classifier" -> ""    
    | "Container" -> ""    
    | "ControlFlow" -> ""
    | "Gaurd" -> "" //Guard maybe?
    | "Name" -> Name item
    | "ObjectFlow" -> ""    
    | "Source" -> ""    
    | _ -> ""

以下是使用Item的简单定义(使用repl显示)的工作示例:

> type Item() =
    member val name = "" with get,set
type item = Item

let Name (itemParameter:item) = itemParameter.name

let test = item();;
test.name <- "test"
Name test;;

val it : string = "test"