如何调试对象初始化程序代码? [英] How to debug object initializer code?

查看:120
本文介绍了如何调试对象初始化程序代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以逐步在Visual Studio中调试对象初始化程序代码?

Is there a way to step by step debug the object initializer code in Visual Studio?

示例:

return new Veranstaltung()
            {
                ID = tblVeranstaltung.VeranstaltungsID,
                Titel = tblVeranstaltung.Titel,
                KursNummer = tblVeranstaltung.Kursnummer,
                ErsterTermin = tblVeranstaltung.ersterTermin,
                Dauer = tblVeranstaltung.schulungsTage,
                StartZeit = tblVeranstaltung.BeginnZeit,
                EndZeit = tblVeranstaltung.Endzeit,
                KostenNettoValue = tblVeranstaltung.PreisNetto ?? default(decimal),
                IsLastMinute = tblVeranstaltung.lastMinute == 1,
                IsVerkuerzt = tblVeranstaltung.istVerkuerzt == 1,
                IsGeschlossen = tblVeranstaltung.istGeschlosseneVeranstaltung == 1,
                IsIntern = tblVeranstaltung.istInterneVeranstaltung == 1,
                StandortID = Convert.ToInt32(tblVeranstaltung.StandortID),
                LastMinuteRabatt = tblVeranstaltung.lastMinuteRabatt ?? default(decimal)
            };

有时我会在这种代码中遇到错误(例如,当转换为int失败时),而VS似乎无法逐步执行它,这只会在整行中引发错误,因此我必须尝试初始化失败.

Sometimes I get errors in this kind of code (for example when a conversion to int fails) and VS seems to be unable to step through it, it just throws an error for the whole line and I have to try out which of the initializations failed.

是否有一种简便的方法可以调试此代码?还是避免针对大型或复杂的初始化使用对象初始化程序更好?

Is there an easy way to debug this or is it better to avoid the object initializer for large or complex initializiations?

我正在使用VS 2010和C#4.0.

I am using VS 2010 and C# 4.0.

推荐答案

应保留对象初始化程序,以进行简单的对象初始化.如果您的对象构造函数具有可能会失败的代码(例如引发异常),请不要使用它.更好地依赖对象构造模式,根据您的需要,它可以是工厂方法,抽象工厂等. 这也确保了您的所有类用户都无法构建处于无效状态的实例(例如,他们忘记初始化成员,或者使用不正确的值初始化相关成员,等等)

Object initializers should be kept for simple object initialization. If you are in the point where your object constructor has code that may fail (e.g. throwing an exception), don't use it. Better rely on an object construction pattern, which depending on your needs may be a factory method, an abstract factory,etc... This also ensures that all the users of your class cannot build an instance that is in an invalid state (e.g. they forget to initialize a member, or they initialize related members with incorrect values, etc...)

这篇关于如何调试对象初始化程序代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆