【问题标题】:Visual Studio , How to display an array of variables in debug modeVisual Studio,如何在调试模式下显示变量数组
【发布时间】:2021-09-27 17:41:12
【问题描述】:

假设我们有一个带有实例变量 randomVariable 的 RandomClass 类:

  public class RandomClass { 
     public int randomVariable ;
     public RandomClass(int _randomVariable){
      randomVariable = _randomVariable;
    }

  }

现在我们有一个 RandomClass 列表:

 void Main(){
  List<RandomClass> randomClassList = new List<RandomClass>();
  int count = 0 ;
   while(count<1000){
    randomClassList.Add(count++);

    }
 }

问题是,在调试模式下,如果我想遍历每个 randomClass 的所有 randomVariable,尤其是如果变量嵌套在其他实例变量中的更深处,我将不得不为每个列表组件进行大量单击。 有没有更好的方法来显示这样的列表组件变量:

randomClassList[0].randomVariable = 0; 
randomClassList[1].randomVariable = 1; 
randomClassList[2].randomVariable = 2; 
randomClassList[3].randomVariable = 3; 
randomClassList[4].randomVariable = 4; 
randomClassList[5].randomVariable = 5; 
randomClassList[6].randomVariable = 6; and so on 

【问题讨论】:

  • 您可以使用DebuggerDisplay 属性来控制调试器如何显示特定类型,但这可能对您的列表没有帮助。您希望它如何显示?
  • 这与 ToString 方法类似,但我的目标是类似的解决方案,但添加代码应处于调试模式,无需对代码进行任何永久修改。
  • 您可以在监视窗口中使用适当的表达方式
  • 你能给我一个例子来说明你如何做这样的事情:``` foreach(var value in list) Display(value.variablex.variabley); ```在调试模式下创建显示方法的地方

标签: visual-studio debugging


【解决方案1】:

您只能在监视窗口中使用表达式,而不能使用语句。但是,鉴于您的List&lt;RandomClass&gt;,以下工作:

// Put this in the watch window:
string.Join(',', randomList.Select(x => x.randomVariable))

如果您收到“选择不是List&lt;RandomClass&gt; 的成员”的错误消息,请将using System.Linq 添加到您的源文件中,即使它没有在实际代码中使用。

【讨论】:

  • 这适用于 lambda 但是,当我使用 lambda 时,它说节点不支持 x =>x.randomVariable ,我正在使用 Linq
  • 为我工作。要么您有拼写错误,要么您使用的不是列表。如果表达式太复杂(例如在字典上尝试),表达式可能会失败
猜你喜欢
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 2020-02-09
  • 2016-03-17
相关资源
最近更新 更多