缓存抽象类的propertyinfo
我一直在尝试实现一个抽象基类,该基类使用反射完成 SQL 到对象的映射。
我做了一些基准测试,并决定对对象的属性信息实施缓存策略(以防止将来对其进行查找)。我的第一直觉是尝试实施这样的事情。
Public MustInherit Class BaseModel
Implements IFillable
Private Shared PropertyCache As List(Of PropertyInfo)
Sub New()
PropertyCache = New List(Of PropertyInfo)
For Each itm As PropertyInfo In Me.GetType().GetProperties
PropertyCache.Add(itm)
Next
End Sub
End Class
但后来我意识到这显然行不通,因为它会在后续的对象实例化中被覆盖。
所以现在我陷入困境,如何实现一个缓存其反射“元数据”的抽象类?
编辑:
这是我能想到的最好的(解决我的问题的方法),我希望有人能提出更好的建议?
Public MustInherit Class BaseModel
Implements IFillable
Private Shared ReadOnly PropertyCache As New Dictionary(Of String, PropertyInfo)
Sub New()
Dim typeName As String = Me.GetType.ToString
For Each itm As PropertyInfo In Me.GetType().GetProperties
Dim lookupKey As String = String.Format("{0}_{1}", typeName, itm.Name)
If Not PropertyCache.ContainsKey(lookupKey) Then
PropertyCache.Add(lookupKey, itm)
End If
Next
End Sub
End Class
I've been playing around with implementing an abstract base class that using reflection accomplishes SQL to Object mapping.
I did some benchmarks and decided I wanted to implement a caching strategy for the property info of the objects (to prevent future lookups on them). My first instinct was to try and implement something like this.
Public MustInherit Class BaseModel
Implements IFillable
Private Shared PropertyCache As List(Of PropertyInfo)
Sub New()
PropertyCache = New List(Of PropertyInfo)
For Each itm As PropertyInfo In Me.GetType().GetProperties
PropertyCache.Add(itm)
Next
End Sub
End Class
but then I realized that this would obviously not work because it would get overridden on subsequent object instantiations.
So now Im stuck, how can you implement an abstract class that caches its reflection "metadata"?
EDIT:
This is the best (workaround to my problem) I can come up with, Im hoping someone can suggest something better?
Public MustInherit Class BaseModel
Implements IFillable
Private Shared ReadOnly PropertyCache As New Dictionary(Of String, PropertyInfo)
Sub New()
Dim typeName As String = Me.GetType.ToString
For Each itm As PropertyInfo In Me.GetType().GetProperties
Dim lookupKey As String = String.Format("{0}_{1}", typeName, itm.Name)
If Not PropertyCache.ContainsKey(lookupKey) Then
PropertyCache.Add(lookupKey, itm)
End If
Next
End Sub
End Class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将代码放置在 Shared Sub New 中,那么它应该只执行一次。
http://msdn.microsoft.com/en-我们/library/aa711965(v=vs.71).aspx
If you place the code in Shared Sub New instead it should only execute once.
http://msdn.microsoft.com/en-us/library/aa711965(v=vs.71).aspx