在C#中使用对象初始化程序时,无法识别引发异常的属性 [英] Cannot Identify the property which throw exception when using Object initializer in C#

查看:112
本文介绍了在C#中使用对象初始化程序时,无法识别引发异常的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的两个示例代码中,我试图通过使用C#常规方法和对象初始化程序来实例化名为 Test 的类.

In the below two sample code I am trying to instantiate a class named Test by using C# normal method and Object initializer.

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;

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

In the above sample code, I can clearly understand which property is showing exception while debugging.

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
};

在上面的代码中,当我使用对象初始化程序时,我无法理解哪个属性引发了异常.在这里,我无法逐行调试.如果我初始化了很多属性,则很难识别.

In this above code, when I use object initializer I couldn't understand which property is thrown exception. Here I couldn't debug line by line. If I have lot of properties initialized it's very difficult to identify.

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

Here is my question: How can I identify which property is showing exception from exception window? Right now the inner exception is null.

推荐答案

对象初始化程序应用于简单的初始化.在具有引发异常的代码的地方,您会遇到问题所描述的情况.

Object initializers should be used for simple initialization. Where you have a code that throws an exception, you will run into described by you issues.

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

I know this is not really an answer, but you will not know which property fails. In case of nullables you could use something like this, where you specify the default value.

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

这篇关于在C#中使用对象初始化程序时,无法识别引发异常的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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