使用对象初始化程序时如何正确使用断点? [英] How can I properly use breakpoints when using an object initializer?

查看:253
本文介绍了使用对象初始化程序时如何正确使用断点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,执行以下操作:

foreach (DataRow row in data.Rows)
{
    Person newPerson = new Person()
    {
        Id = row.Field<int>("Id"),
        Name = row.Field<string>("Name"),
        LastName = row.Field<string>("LastName"),
        DateOfBirth = row.Field<DateTime>("DateOfBirth")
    };

    people.Add(newPerson);
}

无法为单个分配设置断点,该断点被设置为整个块.

Setting a breakpoint to an individual assignation is not possible, the breakpoint is set to the entire block.

如果我想具体查看我的代码在哪里中断,我必须使用:

If I want to see specifically where my code is breaking, I have to use:

 foreach (DataRow row in data.Rows)
 {
     Person newPerson = new Person();
     newPerson.Id = row.Field<int>("Id");
     newPerson.Name = row.Field<string>("Name");
     newPerson.LastName = row.Field<string>("LastName");
     newPerson.DateOfBirth = row.Field<DateTime>("DateOfBirth");

     people.Add(newPerson);
 }

或者也许我缺少了一些东西. 使用对象初始化程序可以正确调试吗?

Or maybe I'm missing something. Can you properly debug when using an object initializer?

推荐答案

对象初始化程序只是语法糖,在编译时会进行翻译.您原始的对象初始值设定项将变成这样:

Object initializers are just syntactic sugar and get translated when they're compiled. Your original object initializer becomes something like this:

var temp = new Person();
temp.Id = row.Field<int>("Id");
temp.Name = row.Field<string>("Name");
temp.LastName = row.Field<string>("LastName");
temp.DateOfBirth = row.Field<DateTime>("DateOfBirth");
var person = temp;

由于整个代码块都这样翻译,因此您不能在一个步骤之内中断.如果您绝对需要中断某个特定步骤,则可以选择几种方法.

Since the whole block is translated like that you can't break inside one step. If you absolutely need to break on one particular step, you have a few options.

  1. 将其分解.调试时不要使用对象初始值设定项,您可以将它们放回后缀.

  1. Break it up. Don't use object initializers while debugging, and you can put them back afterwords.

临时变量.

方法调用.您可以将一些代码包装在自定义方法调用中,仅允许您在自定义方法内添加断点.您甚至可以像这样概括它:

Method call. You can wrap some of the code in a custom method call solely to allow you to add a breakpoint within your custom method. You could even generalize it like this:

    Id = BreakThenDoSomething(() => row.Field<int>("Id"));

    public static T BreakThenDoSomething<T>(Func<T> f)
    {
        Debugger.Break();
        return f();
    }

这篇关于使用对象初始化程序时如何正确使用断点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆