How can I properly use breakpoints when using an object initializer?

安稳与你 提交于 2019-12-12 09:47:08

问题


For example, doing something like this:

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?


回答1:


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. Break it up. Don't use object initializers while debugging, and you can put them back afterwords.

  2. Temp variables. Instead of assigning Id = row.Field<int>("Id") directly, assign row.Field<int>("Id") to a temp variable first (or whichever one you want to debug) and then assign the temp variable to the object initializer property.

  3. 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();
    }


来源:https://stackoverflow.com/questions/5112782/how-can-i-properly-use-breakpoints-when-using-an-object-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!