c# - 来自 list<object> , ToString() 它们只是当它们是原始类型或重写此方法时

标签 c# .net vb.net tostring

给定一个对象列表,我想打印它们的字符串版本,以防 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/

相关文章:

c# - 如何在 Protobuf 中实现 VARIANT

c# - EF 迁移和时间戳列,无法更新/运行

.net - 将反射 .GetValue() 对象强转换为通用 DbSet

vb.net - 如何将事件处理程序添加到 VB.NET 中的局部变量

c# - Web 服务 Excel 转换

c# - 尽管已经执行了依赖于 Func`2 的代码,但 WinCE 上的 Func`2<> 出现 MissingMethodException

c# 循环直到 Console.ReadLine = 'y' 或 'n'

c# - WPF - 检测转换器中的设计模式

.net - 总是使用 Form.Invoke() 是一种不好的做法吗?

c# - 为什么调试器的断点条件允许赋值语句作为 bool 条件?