在 C# 中使用对象初始值设定项时无法识别抛出异常的属性

Cod*_*-EZ 5 c# exception object-initializers

在下面的两个示例代码中,我试图通过使用 C# 普通方法和对象初始值设定项来实例化一个名为Test的类。

DateTime? nullDate = null; //this value will come from somewhere else
DateTime? notNullDate = DateTime.Now;
var test = new Test();
test.Date = nullDate.Value; //exception will throw here
test.Name = "String";
test.AnotherDate = notNullDate.Value;
Run Code Online (Sandbox Code Playgroud)

在上面的示例代码中,我可以清楚地了解调试时哪个属性显示异常。

DateTime? nullDate = null; //this value will come from somewhere else
DateTime? notNullDate = DateTime.Now;
var test = new Test
{
    Date = nullDate.Value,
    Name = "String",
    AnotherDate = notNullDate.Value
};
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,当我使用对象初始值设定项时,我无法理解抛出异常的属性。在这里,我无法逐行调试。如果我初始化了很多属性,则很难识别。

这是我的问题:如何从异常窗口识别哪个属性显示异常?现在内部异常为空。

在此处输入图片说明

Rol*_*and 0

对象初始值设定项应用于简单的初始化。如果您有抛出异常的代码,您将遇到您所描述的问题。

我知道这并不是一个真正的答案,但你不会知道哪个属性失败了。如果可以为空,您可以使用类似的方法,在其中指定默认值。

var test = new Test
        {
            Date = nullDate.GetValueOrDefault(new DateTime()),
            Name = "String",
            AnotherDate = notNullDate.Value
        };
Run Code Online (Sandbox Code Playgroud)

  • 您可以参考此答案以获得好处:http://stackoverflow.com/questions/12842371/is-there-any-benefit-of-using-an-object-initializer (2认同)