如何在LINQ中处理新运算符中的异常?

时间:2014-02-21 06:43:45

标签: c# linq exception

我需要在LINQ中处理异常,但我不知道如何做到这一点。这是我的代码:

    return (from element in m_Content.Descendants(Properties.Settings.Default.DataSourceTag)
            select new DataSource
            {
                Provider = Provider.Parse(element.Attribute(Properties.Settings.Default.SpProvider).Value),
                Template = element.Attribute(Properties.Settings.Default.TemplateAttribute).Value,
                Reference = element
            });

那么,数据源属性中的问题。如果其中一个或多个为空,我怎么能抓住?

由于

2 个答案:

答案 0 :(得分:1)

不是直接访问Value属性,而是使用显式强制转换。例如,将其强制转换为字符串或Template的任何类型。

Template =(string)element
         .Attribute(Properties.Settings.Default.TemplateAttribute),

如果没有NullReferenceException

,它会避免Attribute.

答案 1 :(得分:0)

LINQ使用defered execution。因此,您在问题中引用的行执行构造函数,并且不会抛出异常。

执行LINQ查询时将抛出异常。 此时,您需要添加try-catch块。

示例:

IEnumerable<DataSource> GetData()
{
    return (from element in m_Content.Descendants(Properties.Settings.Default.DataSourceTag)
        select new DataSource
        {
            Provider = Provider.Parse(element.Attribute(Properties.Settings.Default.SpProvider).Value),
            Template = element.Attribute(Properties.Settings.Default.TemplateAttribute).Value,
            Reference = element
        });   // no exception thrown here
}

void myMethod1()
{
    var data = GetData();    // no exception thrown here

    var lst = data.ToList(); // exception might be thrown here!
}

void myMethod2()
{
    var data = GetData();    // no exception thrown here

    foreach (var entry in data) // exception might be thrown here!
    {
        ...
    }
}
相关问题