Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?

前端 未结 15 1828
暗喜
暗喜 2020-11-27 04:00

The indexer into Dictionary throws an exception if the key is missing. Is there an implementation of IDictionary that instead will return de

15条回答
  •  清酒与你
    2020-11-27 04:54

    One could define an interface for the key-lookup function of a dictionary. I'd probably define it as something like:

    Interface IKeyLookup(Of Out TValue)
      Function Contains(Key As Object)
      Function GetValueIfExists(Key As Object) As TValue
      Function GetValueIfExists(Key As Object, ByRef Succeeded As Boolean) As TValue
    End Interface
    
    Interface IKeyLookup(Of In TKey, Out TValue)
      Inherits IKeyLookup(Of Out TValue)
      Function Contains(Key As TKey)
      Function GetValue(Key As TKey) As TValue
      Function GetValueIfExists(Key As TKey) As TValue
      Function GetValueIfExists(Key As TKey, ByRef Succeeded As Boolean) As TValue
    End Interface
    

    The version with non-generic keys would allow code that was using code using non-structure key types to allow for arbitrary key variance, which would not be possible with a generic type parameter. One should not be allowed to use a mutable Dictionary(Of Cat, String) as a mutable Dictionary(Of Animal, String) since the latter would allow SomeDictionaryOfCat.Add(FionaTheFish, "Fiona"). But there's nothing wrong with using a mutable Dictionary(Of Cat, String) as an immutable Dictionary(Of Animal, String), since SomeDictionaryOfCat.Contains(FionaTheFish) should be considered a perfectly well-formed expression (it should return false, without having to search the dictionary, for anything that isn't of type Cat).

    Unfortunately, the only way one will be able to actually use such an interface is if one wraps a Dictionary object in a class which implements the interface. Depending upon what you're doing, however, such an interface and the variance it allows might make it worth the effort.

提交回复
热议问题