2011년 4월 14일 목요일

C# Extension Method

1. 확장 메서드를 아래와 같이 작성한다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    public static class Extension
    {
        public static string ToJson(this Object o)
        {
            var serializer = new JavaScriptSerializer();
            return serializer.Serialize(o);
        }
    }
}

2. 데이터 클래스를 작성하고 작성한 확장 메서드를 이용
(확장 메서드 : 데이터 객체를 Json으로 serialize를 해주는 기능)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataClass d = new DataClass();
            Console.WriteLine(d.ToJson());
        }

    }

    class DataClass
    {
        public DataClass() 
        {
            id = new Guid();
            name = "RJD2";
            title = "C#";
            content = "Extension Method";
        }

        public Guid id { get; set; }
        public string name { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        
    }
}

3. 메서드를 사용할 때 vs에서 자동완성을 지원한다~

댓글 없음:

댓글 쓰기