c# - 调试序列化期间消耗的 yield 返回的最佳方法?

标签 c# visual-studio debugging serialization

我正在开发一个在页面中嵌入 JSON 的应用程序。一些简化的例子:

public ViewResult Page(IEnumerable<LolCat> lolCats)
{
    var json = new
    {
        localCats = ToJson(lolCats),
    };

    return View( json ); // this gets serialized somewhere in the ASP pipeline
}

IEnumerable<object> ToJson(IEnumerable<LolCat> lolCats)
{
    foreach ( var lolCat in lolCats )
        yield return new { name = lolCat.name };
}

JSON 在 ASP.NET 管道中的某处自动序列化

在此示例中,假设有时 NULL 会滑入 lolCats,从而引发异常。问题是 ToJson 函数可能会在整个应用程序的许多不同位置被调用。

我如何找出对 ToJson 的调用是导致异常的调用?调用堆栈在实际使用此 IEnumerable 的序列化程序中结束,因此您看不到 < strong>'原始堆栈跟踪'。

The call stack ends in the Serializer that is actually consuming this IEnumerable, and therefore that's not working

一个简单的修复方法是在 Page 中调用 ToList()。但我正在寻找一种不会破坏方法惰性的方法。

最佳答案

由于延迟的性质,您永远不会知道对 ToJson() 的调用实际上产生了异常。在第一次枚举(当它被序列化时)之前,该集合从未被首先检查过。

您需要向您的枚举器中注入(inject)一些关于调用它的信息。

例如,

IEnumerable<object> ToJson(IEnumerable<LolCat> lolCats, string id)
{
    try
    {
        foreach (var lolCat in lolCats)
            yield return new { name = lolCat.name };
    }
    catch (Exception ex)
    {
        throw new Exception(id, ex); // use a more appropriate exception
    }
}

然后只需生成一个可以帮助识别调用者的 id 即可。

关于c# - 调试序列化期间消耗的 yield 返回的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32426302/

相关文章:

Java 相当于 NetworkCredential

c# - Control.Dispatcher.BeginInvoke() 和 Control.Dispatcher.Invoke() 顺序执行是不是很困惑?

javascript - 如何调试 gulpfile.js

.net - 如何在登台服务器中调试 .net dll 程序集

c - 奇怪的fluidsynth断言( 'settings != NULL')结果

c# - 在 SharePoint 计时器作业中创建发布页面会引发 MissingMethodException

c# - 使用 JSONP 和 JQuery 调用 REST Api

c++ - gcc 中是否有 stdext::hash_map 的等价物

c++ - 警告 C6273 : Non-integer passed as _Param_(2) when an integer is required

visual-studio - 在保留公共(public)控件功能的同时禁用 list 中的视觉样式