开发者

Add entry to list while debugging in Visual Studio

I have a point in my code where I have added a breakpoint. What I would like to do when the debugger stops at the break point is to modify the contents of a list (specifically in this case I want to add entries).开发者_Python百科 How do I modify the contents of a list while debugging?

Edit: The list is a list of strings.


Use the immediate window (default of CTRL+D,I with C# keybindings, or it's in the Debug > Windows menu).

From there just invoke myList.Add(foo), it will come back saying the expression has been evaluated and has no value, but the side effect of adding foo occurs.


Also in the watch window you can perform single-line statements (or better expression).

Just write something like:

myList.Add("myNewValue")

and press ENTER It should works (at least has always worked for me )


There is a technique that you can use to inject code from within a breakpoint. It's easy, and it works.

  1. Set a breakpoint
  2. Right-click on the breakpoint, and choose "conditions"
  3. Put your line of code in the condition (it does not have to return a bool)
  4. Run

When your breakpoint is hit, the code will execute, and the debugger will NOT stop on the breakpoint (because you didn't return a bool).

I got this tip from the Visual Studio tips blog: Link

Here's an example program that illustrates the technique:


        static void Main(string[] args)
        {
            List l = new List();
            Console.WriteLine(l[0]);
            System.Console.ReadLine();
        }

If you run this code as-is, you will get an exception. However, before yourun it, add a breakpoint to hte Console.WriteLine() line.

Right-click on the breakpoint, and choose "conditions" In the condition dialog, add the following code:

l.Add("hello")

Now run.

Clearly, a person could get into a lot of trouble with this "feature" -- you can change the behavior of your application with breakpoints such that an independent build of the code behaves differently from when it is run on your machine in your debugger. So, be very careful...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜