Вопрос

Есть ли способ исправить шаг отладить код инициализатора объекта в 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, похоже, не может пройти через него, он просто бросает ошибку для всей линии, и я должен попробоватьИнициализации не удалось.

Есть ли простой способ отлаживать это или лучше избегать инициализатора объекта для больших или сложных инициализаций?

Я использую vs 2010 и 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...)

Другие советы

or is it better to avoid the object initializer for large or complex initializiations?

Yes, it becomes hard to maintain (and debug).

The debugging support for object initializers isn't very good in Visual Studio 2010. It may be pragmatic to avoid using object initializers for large or complex initializiations for that reason, but I don't consider using large or complex (e.g. nested) object initializations a bad design choice in and of itself.

I have found that for mapping objects that represent documents/records (like your example), it makes for a very readable declarative style, minimizing "noise" in the code, and allowing the reader to more clearly see the relationship between the source and target. This approach also encourages a separation of data mapping from data validation, which I think is desirable.

A null-safe dereference operator would also help a lot when coding in this style, but that's another topic! Hopefully, a future relase of Visual Studio may improve the debugging of these useful constructs.

Not sure whether it's possible in Visual Studio 2010, but in Visual Studio 2017, you can do that by disabling the option to step over property setters in Visual Studio Debug settings:

enter image description here

Step Into (F11) works while debugging in VS2015 and up, without any configuration.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top