在F#中如何使用(从键中获取值,添加项目)哈希表 [英] How do you use (get values from keys, add items) Hashtables in F#

查看:55
本文介绍了在F#中如何使用(从键中获取值,添加项目)哈希表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在F#中使用System.Collections.Hashtable.它是哈希表的原因是因为我引用的是C#程序集.

我将如何调用以下方法? - 添加 -从钥匙中获取价值

我在Google上找不到任何有用的东西.

正如Mark所指出的,您可以直接从F#使用Hashtable类型(就像使用任何其他.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] 

由于Hashtable不是通用的,因此您可能希望将对象转换回字符串.为此,可以使用:?>向下运算符,也可以使用unbox关键字并提供类型注释,以指定要作为结果获得的类型:

let s = (sObj :?> string)
let (s:string) = unbox sObj

如果您可以控制使用哪种类型,那么我建议使用Dictionary<int, string>而不是Hashtable.这与C#完全兼容,因此您无需进行强制转换.如果要从F#返回此结果,则还可以使用标准F#map并在将其传递给C#之前将其上传到IDictionary<_,_>:

let map = Map.empty |> Map.add 1 "one"
let res = map :> IDictionary<_, _>

这样,C#用户将看到一个熟悉的类型,但是您可以按照通常的功能样式编写代码.

I would like to know how to use a System.Collections.Hashtable in F#. The reason it is a Hashtable is because I am referencing C# assemblies.

How would I call the following methods? - Add - Get value from key

I have not been able to find anything useful in Google about this.

解决方案

As Mark points out, you can work with the Hashtable type directly from F# (just like with any other .NET type). The syntax for accessing indexers in F# is slightly different though:

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] 

Since Hashtable is not generic, you would probably want to cast the object back to string. To do that, you can either use the :?> downcast operator, or you can use the unbox keyword and provide a type annotation to specify what type do you want to get as the result:

let s = (sObj :?> string)
let (s:string) = unbox sObj

If you have any control over what type is used, then I would recommend using Dictionary<int, string> instead of Hashtable. This is fully compatible with C# and you would avoid the need to do casting. If you're returning this as a result from F#, you could also use standard F# map and just upcast it to IDictionary<_,_> before passing it to C#:

let map = Map.empty |> Map.add 1 "one"
let res = map :> IDictionary<_, _>

This way, C# users will see a familiar type, but you can write the code in the usual functional style.

这篇关于在F#中如何使用(从键中获取值,添加项目)哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆