【问题标题】:F# Dictionary of OptionsF# 选项字典
【发布时间】:2016-02-13 09:48:27
【问题描述】:

为什么我不能将 None 添加到 System.Collections.Generic.DictionaryOption 中?这是 Mono 中的预期行为还是错误?

F# Interactive for F# 3.1 (Open Source Edition)
Freely distributed under the Apache 2.0 Open Source License

For help type #help;;

> open System.Collections.Generic;;
> let d1 = new Dictionary<int option, int>();;

val d1 : Dictionary<int option,int> = dict []

> d1.Add(None, 1);;
System.ArgumentNullException: Value cannot be null.
Parameter name: key
   at System.ThrowHelper.ThrowArgumentNullException (ExceptionArgument argument) in <filename unknown>:line 0
   at System.Collections.Generic.Dictionary`2[TKey,TValue].Insert (System.Collections.Generic.TKey key, System.Collections.Generic.TValue value, Boolean add) in <filename unknown>:line 0
   at System.Collections.Generic.Dictionary`2[TKey,TValue].Add (System.Collections.Generic.TKey key, System.Collections.Generic.TValue value) in <filename unknown>:line 0
   at <StartupCode$FSI_0004>.$FSI_0004.main@ () in <filename unknown>:line 0
   at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
   at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) in <filename unknown>:line 0
Stopped due to error
> d1.Add(Some 10, 1);;
val it : unit = ()

我在 OS X 上使用 Mono。

$ mono --version
Mono JIT compiler version 4.2.0 (Stable 4.2.0.179/a224653 Tue Oct  6 11:28:25 PDT 2015)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           normal
    SIGSEGV:       altstack
    Notification:  kqueue
    Architecture:  amd64
    Disabled:      none
    Misc:          softdebug
    LLVM:          supported, not enabled.
    GC:            sgen

【问题讨论】:

  • 试试let d1 = new Dictionary&lt;int option, int&gt;(HashIdentity.Structural)
  • @Ming-Tang 不幸的是,正如 Kevin 所指出的,这是所期望的行为。常规 Dictionary&lt;_,_&gt; 不接受 null 作为键。另一方面,F# 的 Map&lt;_,_&gt; 按预期工作,但我知道它可能不是合适的替代品。

标签: dictionary f# mono


【解决方案1】:

这不是错误。 Option 使用属性 [CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue) 导致 None 被表示为 null。

因此,您实际上是在向 Dictionary 添加一个 null 作为键,而您知道这是不允许的。

供参考:

UseNullAsTrueValue: 允许在可区分联合中使用 null 作为 null 鉴别器的表示。

更多信息在这里Why is None represented as null?

【讨论】:

    猜你喜欢
    • 2014-05-10
    • 2012-09-20
    • 2016-04-12
    • 2011-03-17
    • 2012-04-20
    • 1970-01-01
    • 2020-07-07
    • 2020-12-25
    • 1970-01-01
    相关资源
    最近更新 更多