31 Partial

vencott·2021년 6월 2일
0

C#

목록 보기
31/32

C# 2.0부터 Partial Type, Partial Struct, Partial Interface를 사용할 수 있다

Partial 타입이 만들어진 이유는 Code Generator가 만든 코드와 사용자가 만든 코드를 구분하기 위함

ASP.NET 웹폼에서 하나의 웹페이지를 만들 때, page1.aspx / page1.aspx.designer.cs / page1.aspx.cs 와 같이 3개의 파일을 만드는데, XML인 aspx 파일을 제외하고 나머지 .cs 파일 안에서 각각 partial class로 개발 후 컴파일러가 이를 나중에 합친다

웹 개발자는 Code Behind라 불리우는 page1.aspx.cs 파일에서 주로 작업한다

Partial 기능은 개발자에게 포커스 해야하는 코드를 분리해 준다는 점에서 큰 도움이 된다

partial 키워드는 class, struct, interface 키워드 바로 앞에 위치해야하며 2개 이상의 파일에 걸쳐 Type을 나눌 수 있게 한다

// 1. Partial Class - 3개로 분리한 경우
partial class Class1
{
    public void Run() { }
}

partial class Class1
{
    public void Get() { }
}

partial class Class1
{
    public void Put() { }
}
// 2. Partial Struct
partial struct Struct1
{
    public int ID;
}

partial struct Struct1
{
    public string Name; // 원래는 필드끼리 한군데 모아 두는 것이 권장사항

    public Struct1(int id, string name)
    {
        this.ID = id;
        this.Name = name;
    }
}
// 3. Partial Interface
partial interface IDoable
{
    string Name { get; set; }
}

partial interface IDoable
{
    void Do();
}

public class DoClass : IDoable
{
    public string Name { get; set; }

    public void Do()
    {
    }
}

Partial Method

C# 3.0에서는 C# 2.0에서 소개된 3개의 partial type들 외에 Partial Method를 새롭게 추가하였다

Partial Method는 전제 조건으로 메서드가 반드시 private이어야 하며 리턴값이 없어야(void) 한다

// 첫번째 클래스에 DoThis 메서드의 선언부만 적고 두번째 클래스에서 구현한다
// 만약 두번째 클래스에서 구현 부분이 생략될 경우 컴파일러는 DoThis() 전체를 없애버린다
public partial class Class2
{
    public void Run()
    {
        DoThis();
    }

    // 조건1: private only
    // 조건2: void return only
    partial void DoThis();
}

public partial class Class2
{
    partial void DoThis()
    {
        Log(DateTime.Now);
    }
}

출처: http://www.csharpstudy.com/

profile
Backend Developer

0개의 댓글