简体   繁体   English

在Visual Studio 2010调试器中修改托管代码的方法返回值

[英]Modifying method return value for managed code in Visual Studio 2010 debugger

Say I have this C# method: 说我有这个C#方法:

public bool GetVal()
{
    return a1 == b1 || c1 == d1 || GetE1() == GetF1(); // Illustrating complicated logic here..
}

I don't want to modify the content of the variables / return values of methods in the statement above, but want to return false to the method that's calling GetVal() . 我不想在上面的语句中修改变量的内容/方法的返回值,但想向调用GetVal()的方法返回false。

Is it possible to use the VS2010 debugger to somehow modify the return value in the same way that I can modify variable values on the fly? 是否可以使用VS2010调试器以某种方式修改返回值,就像我可以即时修改变量值一样? Perhaps modifying the call stack somehow? 也许以某种方式修改调用堆栈?

It's not possible to modify the return value directly in this manner. 以这种方式不可能直接修改返回值。 Managed code has very limited / no support for seeing the return value of a function call as compared to C++. 与C ++相比,托管代码非常有限/不支持查看函数调用的返回值。

But what you can do is go to the call site and modify the variable which is assigned the value of function call. 但是您可以做的是转到调用站点并修改为函数调用赋值的变量。

public bool GetVal()
{
    bool retval = a1 == b1 || c1 == d1 || GetE1() == GetF1();
// edit retval to be 'false' in the debugger now
    return retval;
}

I often find myself needing the same thing, unfortunately the only way to do this is to create a temporary variable which you can change via the Locals or Watch window before the function returns. 我经常发现自己需要同样的东西,不幸的是,唯一的方法是创建一个临时变量,您可以在函数返回之前通过Locals或Watch窗口进行更改。

public bool GetVal()
{
    bool b = a1 == b1 || c1 == d1 || GetE1() == GetF1();
    return b;//Set breakpoint here
}
public bool GetVal()
{
    var result = a1 == b1 || c1 == d1 || GetE1() == GetF1(); // Illustrating complicated logic here..
    return result;
}

Set breakpoint on return line and modify result variable. 在返回线上设置断点并修改结果变量。

As the other answers noted: 其他答案指出:

public bool GetVal()
{
    bool result = a1 == b1 || c1 == d1 || GetE1() == GetF1();
    return result;
}

Works perfectly. 完美运作。 However, in general code that strings together huge lines of if statements are much harder to read and debug anyway. 但是,在通常的代码中,将庞大的if语句组合在一起的代码无论如何都很难阅读和调试。

You should be breaking your function into steps rather than having it perform all of the steps in one line. 您应该将功能分成几步,而不是让它一行执行所有步骤。

Another method to accomplish your task would be to set a breakpoint in your code at if(GetVal()) and simply modify the execution path from there, rather than trying to modify the return value, simply modify the state of affairs where the value is used . 完成任务的另一种方法是在代码中的if(GetVal())处设置一个断点,然后从那里简单地修改执行路径,而不是尝试修改返回值,只需修改值是用过的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM