This small snippet of code is to increment a count value (integer) which is stored in a dictionary using my referenced object as a key. When the dictionary is small, multiple lookups aren't a big deal but this particular dictionary can get quite large.
Private RefCount As IDictionary(Of ILifeTimeManaged, Integer)
......... CODE HERE.....
Private Sub IncrementRefCount(ByVal entity As ILifeTimeManaged)
Dim prevCount As Integer
''# if we have no reference entry, add one and set its count to 1
If Not RefCount.TryGetValue(entit开发者_开发技巧y, prevCount) Then
RefCount.Add(entity, 1)
Else
''# otherwise increment its count by 1
RefCount.Item(entity) = prevCount + 1
End If
End Sub
I find a corresponding dictionary entry then increment the int stored in the value, or add a new dictionary entry.
Is it a bad idea to use a pointer to the dictionary value? Then I can avoid the second key lookup when I already have gotten the value. How would you implement it? Is this even possible in .NET4?
Can I do it using IntPtr do you think? http://msdn.microsoft.com/en-us/library/system.intptr.aspx
RefCount.Item(entity) = prevCount + 1
That does not look like a bad idea.
If you want to improve performance, you may want to add a property RefCount to the ILifeTimeManaged interface and use it instead of using the dictionary. But I don't know your design and goal, so can't say is this apropriate to you.
You cannot make a pointer to any given type in VB like you could in C++. However, you can wrap a value type in a reference type to get the semantics you want.
Public Class Ref(Of T As Structure)
Public Sub New()
End Sub
Public Sub New(ByVal value As T)
Me.Value = value
End Sub
Public Property Value As T
End Class
This lets you return a "pointer" to an integer (more correctly, a reference to something containing an integer). You could then write something like this:
Private RefCount As IDictionary(Of ILifeTimeManaged, Ref(Of Integer))
......... CODE HERE.....
Private Sub IncrementRefCount(ByVal entity As ILifeTimeManaged)
Dim count As Integer
''# if we have no reference entry, add one and set its count to 1
If Not RefCount.TryGetValue(entity, count) Then
RefCount.Add(entity, New Ref(Of Integer)(1))
Else
''# otherwise increment its count by 1
count.Value += 1
End If
End Sub
You could add some conversion methods between T
and Ref(Of T)
to the Ref
class to possibly simplify the syntax (like in the Add call). In my opinion, doing so would give you something closer to C++ references than C++ pointers. Whether that's what you want or not is up to you.
Edit RE your Edit: IntPtr is designed to represent any pointer type in interop code calls. Perhaps a better name would have been NativePtr. There is no way to use an IntPtr in managed code the way I think you want, as you would a pointer in C++.
精彩评论