简体   繁体   English

使用例如 Linq-To-Xml 时处理 null 引用

[英]Handling null references when using eg Linq-To-Xml

Is there a better/shorter way to handle (lots of) null references, for example when I'm using LinqToXML.是否有更好/更短的方法来处理(大量)null 引用,例如当我使用 LinqToXML 时。

I wrote this extention for XElement that handles it quite nicely, but maybe there is another way?我为 XElement 编写了这个扩展,它可以很好地处理它,但也许还有另一种方法?

And what about the function name?那么 function 名称呢? "And" isn't really descriptive. “和”并不是真正的描述性。

public static class XmlExtentions
{
    public static T And<T>(this T obj, Func<T, T> action) where T : XElement
    {
        return obj == null ? obj : action(obj);
    }
}

internal class Program
{
    private static void Main()
    {
        //create example xml element
        var x = 
          XElement.Parse("<root><find><name>my-name</name></find></root>");

        //old way
        var test1 = x.Element("find");
        if (test1 != null) test1 = test1.Element("name");
        Console.WriteLine(test1);

        //using the extentions method
        var test2 = x.Element("find").And(findme => findme.Element("name"));
        Console.WriteLine(test2);

        Console.ReadLine();
    }
}

PS: I know I could use XPath for this example, but that's not always the case in more complex cases. PS:我知道我可以在这个例子中使用 XPath,但在更复杂的情况下并非总是如此。

The overall approach is reasonable - although I'm not sure about the Func<T,T> which seems a bit restrictive.总体方法是合理的 - 尽管我不确定Func<T,T>似乎有点限制。 If you are limiting to returning the same thing, I wonder if just accepting the name ( string ) as the second arg wouldn't be easier?如果您限制返回相同的内容,我想知道是否仅接受名称( string )作为第二个参数会不会更容易?

Re naming - perhaps borrow from LINQ?重新命名 - 也许是从 LINQ 借来的? This is essentaially a Select - how about SelectOrDefault :这本质上是一个Select - SelectOrDefault怎么样:

public static TResult SelectOrDefault<TSource, TResult>(
    this TSource obj, Func<TSource, TResult> selector) where TSource : class
{
    return SelectOrDefault<TSource, TResult>(
        obj, selector, default(TResult));
}

public static TResult SelectOrDefault<TSource, TResult>(
    this TSource obj, Func<TSource, TResult> selector,
    TResult @default) where TSource : class
{
    return obj == null ? @default : selector(obj);
}

(edit) maybe with the additional XElement specific: (编辑)也许与额外的XElement特定:

public static XElement SelectOrDefault(
    this XElement element, XName name)
{
    return element == null ? null : element.Element(name);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM