简体   繁体   English

调试C#对象初始化程序

[英]Debugging a C# Object Initializer

Does anyone have any tips for debugging exceptions in a C# object initializer block? 有没有人有任何调试C#对象初始化程序块中的异常的提示? The object initializer syntax is basically all or nothing, which can make it especially difficult to troubleshoot inside of a LINQ query. 对象初始化器语法基本上是全部或全部,这使得在LINQ查询内部进行故障排除特别困难。 Short of breaking the object creation out to a separate method, is there anything I can do to see which property setter is throwing an exception? 如果没有将对象创建分解为单独的方法,我可以做些什么来查看哪个属性设置器抛出异常?

Disabling the option to step over property setters [Step over properties and operators (Managed Only)] can allow you to step into the property setters. 禁用跳过属性设置器的选项[跳过属性和运算符(仅限管理)]可以允许您进入属性设置器。

Otherwise, the best option is often to just break it out and debug it outside of the LINQ statement. 否则,最好的选择通常是将其分解并在LINQ语句之外进行调试。 You can wrap your initialization parameters into an anonymous type in linq, and construct your object(s) outside of your linq statement for debugging purposes. 您可以将初始化参数包装到linq中的匿名类型中,并在linq语句之外构造对象以进行调试。

Have you set up VS to break when an exception is thrown? 你有没有设置VS在抛出异常时中断? (the default is to break only on unhandled exceptions). (默认情况下仅在未处理的异常时中断)。 Debug | 调试| Exceptions, and check "thrown". 例外,并检查“抛出”。

That alone is probably not an answer to your question, but it might help with the debugging. 仅此一点可能不是您的问题的答案,但它可能有助于调试。

Beyond that, you could temporarily break your code out of the initializer block (just for debugging), and then if you want, you can reinstate the initializer block once you have the code working. 除此之外,您可以暂时将代码从初始化程序块中删除(仅用于调试),然后如果需要,可以在代码运行后恢复初始化程序块。

Break it out of the object initializer block where your setting each property individually. 将其从对象初始化程序块中分离出来,您可以单独设置每个属性。 That way you can actually step into the code. 这样你就可以实际进入代码。

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

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