给定一个对象列表,我想打印它们的字符串版本,以防 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
?
最佳答案
var bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
foreach (var item in coolList)
{
Type t = item.GetType();
if (t.IsPrimitive
|| (t.GetMethod("ToString", bf, null, Type.EmptyTypes, null) != null))
{
Console.WriteLine(item);
}
}
这可能会很慢,因为它使用反射来确定特定类型是否已覆盖 ToString
方法。一种更快的替代方法可能是使用静态缓存来“记住”反射的结果,这样每个类型只需要完成一次:
foreach (var item in coolList)
{
Type t = item.GetType();
if (t.IsPrimitive || _cache.GetOrAdd(t, _factory))
{
Console.WriteLine(item);
}
}
// ...
private static readonly ConcurrentDictionary<Type, bool> _cache =
new ConcurrentDictionary<Type, bool>();
private const BindingFlags _flags =
BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
private static readonly Func<Type, bool> _factory =
t => t.GetMethod("ToString", _flags, null, Type.EmptyTypes, null) != null;
关于c# - 来自 list<object> , ToString() 它们只是当它们是原始类型或重写此方法时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5005286/