从列表
给定一个对象列表,我想打印它们的字符串版本,以防 object.ToString() 结果是相关字符串。
我的意思是我不想得到这样的东西:
obj.ToString() -> System.Collections.Generic.List`1[MyLib.Dude]
obj.ToString() -> System.Collections.Generic.Dictionary`2[System.Int32,System.DateTime]
obj.ToString() -> System.Byte[]
但我想得到这样的东西:
obj.ToString() -> Hi
obj.ToString() -> 129847.123
obj.ToString() -> Id = 123
在方法中实现这个的最好方法应该是什么:
Public Sub PrintInterestingStuffOnly(ByVal coolList as Ilist(Of Object))
For Each obj in coolList
'insert solution here
Console.WriteLine( ....
End For
End Sub
?
Given a list of objects, I'd like to print a string version of them just in case the object.ToString() result is a relevant string.
By that I mean I don't want to get things like:
obj.ToString() -> System.Collections.Generic.List`1[MyLib.Dude]
obj.ToString() -> System.Collections.Generic.Dictionary`2[System.Int32,System.DateTime]
obj.ToString() -> System.Byte[]
But I want to get things like:
obj.ToString() -> Hi
obj.ToString() -> 129847.123
obj.ToString() -> Id = 123
What should be the best way to implement this in a method:
Public Sub PrintInterestingStuffOnly(ByVal coolList as Ilist(Of Object))
For Each obj in coolList
'insert solution here
Console.WriteLine( ....
End For
End Sub
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能会很慢,因为它使用反射来确定特定类型是否已覆盖
ToString
方法。更快的替代方案可能是使用静态缓存来“记住”反射的结果,以便每个类型只需要执行一次:This could be slow since it uses reflection to determine whether or not a particular type has overridden the
ToString
method. A faster alternative might be to use a static cache to "remember" the result of the reflection so that it only needs to be done once per type:如果列表由
{ 1, 2, 3, 4 }
组成,则会打印出:(它将隐式执行
.ToString()
,因此您可以使用任何类型的对象。)If the list was composed of
{ 1, 2, 3, 4 }
, This will print out:(It will perform the
.ToString()
implicitly, so you can use any sort of object.)