如何识别异常日志中的通用对象?

How to identify generic objects in exception logs?

我有一个接受泛型参数的辅助方法。此方法可能会抛出异常,我将其记录下来以便稍后进行调试。有些对象有 ID,有些有名称等,这些在尝试调试时会很有用。如何以有用的方式记录此信息?

不管是不是泛型方法,除非你的对象是null,你可以用myObject.GetType().ToString()

记录类型
Loger.log("Object type that has thrown an error is" + myObj.GetType().ToString());

编辑:

如果您想从对象中读取更多信息,那么您可以像这样读取对象属性:

Type type = myObj.GetType();
List<string> info = new List<String>();
info.Add("Object type that has thrown an error is: " + type.ToString() + Environment.NewLine);
foreach (var prop in type.GetProperties())
{
    if (prop.CanRead)
    {
        info.Add("Name: " + prop.Name + " , Value: " + prop.GetValue(myObj) + Environment.NewLine);
    }
}
Logger.log(string.Join("", info));

这对于原语应该没有任何问题。对于对象,它取决于 ToString 方法的实现方式。另请注意,它不会递归读取,只是 class.

的直接成员

此函数 returns 来自类型的 C# 样式类型名称(类似于 List<String>List<Dictionary<Int32,String>>)。

public static string FancyTypeName(Type type)
{
    var typeName = type.Name.Split('`')[0];
    if (type.IsGenericType)
    {
        typeName += string.Format("<{0}>", string.Join(",",
             type.GetGenericArguments().Select(v => FancyTypeName(v)).ToArray())
           );
    }
    return typeName;
}