问题
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.
Break it up. Don't use object initializers while debugging, and you can put them back afterwords.
Temp variables. Instead of assigning
Id = row.Field<int>("Id")
directly, assignrow.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.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