/
NamedValueMap.vb
65 lines (57 loc) · 3.01 KB
/
NamedValueMap.vb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Public Class NamedValueMap
Implements IEnumerable(Of KeyValuePair(Of InvariantString, Object))
Private ReadOnly _dictionary As New Dictionary(Of InvariantString, Object)
<ContractInvariantMethod()> Private Sub ObjectInvariant()
Contract.Invariant(_dictionary IsNot Nothing)
End Sub
Public Sub New(dictionary As Dictionary(Of InvariantString, Object))
Contract.Requires(dictionary IsNot Nothing)
If (From v In dictionary Where v.Value Is Nothing).Any Then
Throw New ArgumentException("Dictionary contained a null value.", "dictionary")
End If
Me._dictionary = dictionary
End Sub
Public ReadOnly Property ItemRaw(key As InvariantString) As Object
Get
Contract.Ensures(Contract.Result(Of Object)() IsNot Nothing)
If Not _dictionary.ContainsKey(key) Then Throw New InvalidOperationException("No item with key '{0}'".Frmt(key))
Dim result = _dictionary(key)
Contract.Assume(result IsNot Nothing)
Return result
End Get
End Property
<Pure()>
Public Function ItemAs(Of TResult)(key As InvariantString) As TResult
Contract.Ensures(Contract.Result(Of TResult)() IsNot Nothing)
Dim item = Me.ItemRaw(key)
Try
Return DirectCast(item, TResult).AssumeNotNull
Catch ex As InvalidCastException
Throw New InvalidOperationException("Value with key '{0}' has type {1}, not {2}".Frmt(key,
item.GetType,
GetType(TResult)),
innerException:=ex)
End Try
End Function
Public ReadOnly Property ContainsKey(key As InvariantString) As Boolean
Get
Return _dictionary.ContainsKey(key)
End Get
End Property
Public Function ToDictionary() As Dictionary(Of InvariantString, Object)
Contract.Ensures(Contract.Result(Of Dictionary(Of InvariantString, Object))() IsNot Nothing)
Return _dictionary.ToDictionary(keySelector:=Function(pair) pair.Key,
elementSelector:=Function(pair) pair.Value)
End Function
Public Function GetEnumerator() As IEnumerator(Of KeyValuePair(Of InvariantString, Object)) Implements IEnumerable(Of KeyValuePair(Of InvariantString, Object)).GetEnumerator
Return _dictionary.GetEnumerator
End Function
Private Function GetEnumeratorObj() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return GetEnumerator()
End Function
Public Shared Widening Operator CType(dictionary As Dictionary(Of InvariantString, Object)) As NamedValueMap
Contract.Requires(dictionary IsNot Nothing)
Contract.Ensures(Contract.Result(Of NamedValueMap)() IsNot Nothing)
Return New NamedValueMap(dictionary)
End Operator
End Class