如何在VB中过滤泛型集合中指定类型的对象
给定以下类结构:
- Class Base {id}
- Class Derived1 : Base {}
- Class Derived2 : Base {}
- Class MyList : System.Collection.Generic.List(Of Base)
- Class Consumer { list as MyList }
(编辑:将会有超过 2 个派生类,为了简单起见,我只列出了 2 个)
我将以下属性添加到 MyList,尝试回答诸如“找出内部具有指定类型(例如 Derived1)的元素数量之类的问题我的列表?”
Public Overloads ReadOnly Property Count(ByVal objType As System.Type) As Integer
Get
Dim cnt As Integer = 0
For Each o As Object In Me
If (o IsNot Nothing) And (o.GetType.Equals(objType)) Then cnt += 1
Next
Return cnt
End Get
End Property
Q1:有什么需要改进的地方吗?如果是,请指教。
提前致谢
given the following class structures:
- Class Base {id}
- Class Derived1 : Base {}
- Class Derived2 : Base {}
- Class MyList : System.Collection.Generic.List(Of Base)
- Class Consumer { list as MyList }
(edit: there will be more than 2 derived classes, I listed out only 2 for simplicity)
I add the following property to MyList, trying to answer questions like "find out the number of elements with specified type, say Derived1, inside MyList?"
Public Overloads ReadOnly Property Count(ByVal objType As System.Type) As Integer
Get
Dim cnt As Integer = 0
For Each o As Object In Me
If (o IsNot Nothing) And (o.GetType.Equals(objType)) Then cnt += 1
Next
Return cnt
End Get
End Property
Q1: Are there anything to improve? If yes, please advise.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 .NET 3.5,您可以使用 Linq:
根本不需要添加该属性。
In case you use .NET 3.5 you could use Linq:
No need add the property at all.