我想知道如何System.Collections.Hashtable
在F#中使用a .它是Hashtable的原因是因为我引用了C#程序集.
我该如何调用以下方法? - 添加 - 从密钥中获取价值
我无法在Google上找到任何有用的内容.
Tom*_*cek 11
正如Mark指出的那样,您可以Hashtable
直接使用F#中的类型(就像使用任何其他.NET类型一样).在F#中访问索引器的语法略有不同但是:
open System.Collections
// 'new' is optional, but I would use it here
let ht = new Hashtable()
// Adding element can be done using the C#-like syntax
ht.Add(1, "One")
// To call the indexer, you would use similar syntax as in C#
// with the exception that there needst to be a '.' (dot)
let sObj = ht.[1]
Run Code Online (Sandbox Code Playgroud)
由于Hashtable不是通用的,您可能希望将对象强制转换为字符串.要做到这一点,您可以使用:?>
向下转换运算符,也可以使用unbox
关键字并提供类型注释来指定您希望获得哪种类型的结果:
let s = (sObj :?> string)
let (s:string) = unbox sObj
Run Code Online (Sandbox Code Playgroud)
如果您对使用的类型有任何控制权,那么我建议使用Dictionary<int, string>
而不是Hashtable
.这与C#完全兼容,您可以避免进行强制转换.如果你从F#返回这个结果,你也可以使用标准的F#map
并IDictionary<_,_>
在将其传递给C#之前将其翻译为:
let map = Map.empty |> Map.add 1 "one"
let res = map :> IDictionary<_, _>
Run Code Online (Sandbox Code Playgroud)
这样,C#用户将看到熟悉的类型,但您可以使用通常的功能样式编写代码.
归档时间: |
|
查看次数: |
1709 次 |
最近记录: |