为什么我无法将None
添加到System.Collections.Generic.Dictionary
的{{1}}?这是Mono中的预期行为还是错误?
Option
我在OS X上使用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 = ()
答案 0 :(得分:5)
它不是一个错误。选项&LT;&#39; T&GT;使用属性[CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue))导致None被表示为null。
所以你实际上是在为一个字典添加一个null作为你知道不允许的字典。
供参考:
UseNullAsTrueValue: 允许使用null作为歧视联盟中的否定鉴别器的表示。
此处提供更多信息Why is None represented as null?