如何将Null Reference Analysis的结果存入日志文件

时间:2017-03-17 20:33:56

标签: c# exception nullreferenceexception visual-studio-2017

我有以下课程。

class Tim
{
    public Tim()
    {

    }

    public Tom GetTom()
    {
        return new Tom();
    }

}

class Tom
{
    public Tom()
    {

    }

    public Jim GetJim()
    {
        return new Jim();
    }
}

class Jim
{
    public Jim()
    {

    }

    public Jom GetJom()
    {
        return null;
    }
}

class Jom
{
    public Jom()
    {

    }

    public string GetMagicString()
    {
        return "Hello World";
    }
}

其使用如下。

class Program
{
    static void Main(string[] args)
    {
            new Tim().GetTom().GetJim().GetJom().GetMagicString();
    }
}

当我运行它时,抛出Null Reference异常并且新的Null Reference Analysis结果在新的Exception Helper中显示得很漂亮,如下所示。

enter image description here

这很好,因为它清楚地告诉我这个链中的哪个方法调用负责异常。但是,如果这段代码在字段中运行,我还想在日志文件中记录此错误。为此,当我在catch块中捕获NullReferenceException时,我没有获得有关返回null的方法的信息。这个东西只能在VS Exception Helper对话框中使用,此时无法记录吗?

1 个答案:

答案 0 :(得分:3)

  

这是仅在VS Exception Helper对话框中可用的内容,此时无法记录吗?

是的,这只是Visual Studio Exception Helper中提供的内容,此时无法记录。

这实际上不可能,但您必须使用与Visual Studio调试器等效的功能来设置代码。在正常的非检测方案中,没有空引用实际来自何处的记录,因此您的记录输出无法提供该信息。