Metro/Windows 8

C# : LinqToXml 편리한 확장메서드(Extension Method) 만들기

길버트리 2012. 8. 30. 20:19

 

 

상황

 

LinqToXml을 쓰다보면, 엘리먼트나 어트리뷰트가 없는 경우에 대해 null 체크를

귀찮을 정도로 많이 해줘야 안전한 코드가 된다는 것에는 동의하실 겁니다.

 

예를 들면 이런 코드죠.

            var q = from c in xDocument.Descendants("appGroup")
                    select new AppGroup()
                    {
                        Id = c.Attribute("id") == null ? "" : c.Attribute("id").Value,
                        Name = c.Element("name") == null ? "" : c.Element("name").Value,
                        Children = GetApps(c),
                    };

 

Element나 Attribute가 존재하지 않을 때는 string.Empty를 반환하는 메서드가 있으면 얼마나 편할까요?

            var q = from c in xDocument.Descendants("appGroup")
                    select new AppGroup()
                    {
                        Id = c.AttributeOrDefault("id").Value,
                        Name = c.ElementOrDefault("name").Value,
                        Children = GetApps(c),
                    };

 

이렇게 말이예요.

 

 

 

확장메서드

namespace System.Xml.Linq
{
    /// 
    /// Extension methods for XElement
    /// 
    public static class XElementExtensions
    {
        public static XAttribute AttributeOrDefault(this XElement element, XName name)
        {
            var attribute = element.Attribute(name);
            if (attribute == null)
            {
                attribute = new XAttribute(name, "");
            }
            
            return attribute;
        }


        public static XElement ElementOrDefault(this XElement element, XName name)
        {
            var child = element.Element(name);
            if (child == null)
            {
                child = new XElement(name, "");
            }

            return child;
        }
    }
}

 

(예 : XElementExtensions.cs)
이런 확장메서드가 사내 라이브러리에 포함되어 있다면 개발이 더욱 편해지겠죠?

 

 

 

확장메서드 구현팁

 

아, 여기서 팁.

확장메서드를 사용하려면, 확장메서드가 포함된 네임스페이스가 using문으로 선언되어 있어야 합니다.
그런데 어떤 확장메서드가 어떤 네임스페이스에 들어있는 지 금방 알 수도 없고,

알았다 하더라도 코드 상단에 가서 using문 추가하는 일은 쉬운 일이 결코 아닙니다.  

보통은 그래서 만들어 놓은 확장메서드도 존재를 알지 못하고 지나갑니다.


그래서 확장메서드 클래스의 네임스페이스는 확장하려는 클래스와 같은 네임스페이스를 사용하면 좋습니다.

위 예에서는 XElement를 확장하고 있었는데요. XElementExtensions를 정의할 때 XElement와 똑같은 System.Xml.Linq 네임스페이스를 사용했죠.


이미 확장하려는 클래스는 using문이 추가되어 사용이 되고 있는 상황일 테니,

확장메서드는 바로 인텔리센스에 의해 자연스레 노출될 수 있는 상황이 되겠죠! 손 안대고 코를 푸는 매직!

 

 

 

더 볼 것

 

C# 확장 메서드 만드는 방법을 모르시는 분은 아래 링크를 한 번 보시면 됩니다.

http://msdn.microsoft.com/en-us/library/bb383977.aspx

 

 

 

개발 = 창작, 즐거운 개발 인생!