c# – “查看详细信息”窗口不会展开“集合”属性

前端之家收集整理的这篇文章主要介绍了c# – “查看详细信息”窗口不会展开“集合”属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对visual studio有一个小问题.
我有一个抛出CustomException的方法

如果我在try / catch中包装调用方法代码,我可以在调试器中看到异常详细信息

如果我删除try / catch我可以看到“errors”属性有Count = 4但是我看不到错误

这是预期的还是一个错误
我正在使用vs2015 enterprise和.NET 4.5.2

您可以轻松地重现它:
1)用这个创建一个类库

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace ClassLibrary1
  6. {
  7. public static class Class1
  8. {
  9. public static void DoSomethingThatThrowsException()
  10. {
  11. throw new MyException(Enumerable.Range(1,4).Select(e => new MyError() { Message = "error " + e.ToString() }).ToList());
  12. }
  13. }
  14.  
  15. public class MyException : Exception
  16. {
  17. public IEnumerable<MyError> errors { get; set; }
  18. public MyException(IEnumerable<MyError> theErrors) { errors = theErrors; }
  19. }
  20. public class MyError { public string Message { get; set; } }
  21. }

2)创建一个控制台应用程序:

  1. using ClassLibrary1;
  2.  
  3. namespace ConsoleApplicationException
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. try
  10. {
  11. Class1.DoSomethingThatThrowsException();
  12. }
  13. catch (MyException ex)
  14. {
  15. //Here I can expand ex.errors;
  16. }
  17.  
  18. //Here I can see that Count=4 but I cannot see the errors...
  19. Class1.DoSomethingThatThrowsException();
  20.  
  21. }
  22. }
  23. }

PS
我可以使用“DebuggerDisplay”属性解决我的问题,我只是想知道为什么Visual Studio不能按预期工作

  1. [DebuggerDisplay("FullDetails = {FullDetails}")]
  2. public class MyException : Exception
  3. {
  4. public IEnumerable<MyError> errors { get; set; }
  5. public MyException(IEnumerable<MyError> theErrors) { errors = theErrors; }
  6. public string FullDetails { get { return string.Join(",",errors.Select(e => e.Message)); } }
  7. }

更新
如果我将List更改为Array,我有同样的问题,但如果我将其更改为Dictionary,我可以看到第一条记录!

解决方法

我想由于某种原因,编译器在抛出它时无法评估LINQ查询.尝试创建它,然后扔掉它.它允许您在抛出之前计算LINQ查询
  1. public static void DoSomethingThatThrowsException()
  2. {
  3. var ex = new MyException(Enumerable.Range(1,4)
  4. .Select(e => new MyError()
  5. {
  6. Message = "error " + e.ToString()
  7. })
  8. .ToList());
  9. throw ex;
  10. }

猜你在找的C#相关文章