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

谁说我不能喝 提交于 2019-12-05 18:54:22
Samuel Neff

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