partial 키워드

  • C#에서는 C/C++와 달리 cs 파일 하나에 클래스 선언과 정의가 작성
  • 클래스가 커질 경우 가독성이 떨어짐
  • Partial 키워드를 제공함으로써 여러 파일에 하나의 클래스를 작성하도록 허용
  • 대리자(delegate) 또는 열거형(enum) 선언을 할 때 partial 한정자를 사용할 수 없음
// PartialClass1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Partial
{
  partial class PartialClass
  {
    public void PartialClass1()
    {
      Console.WriteLine("PartialClass1 FuncCall");
    }

    // 같은 이름의 메서드는 중복 작성할 수 없음
    public void SameFunc()
    {
      Console.WriteLine("SameFunc");
    }
  }
}
// PartialClass2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Partial
{
  partial class PartialClass
  {
    public void PartialClass2()
    {
      Console.WriteLine("PartialClass2 FuncCall");
    }
 
    // 같은 이름의 메서드는 중복 작성할 수 없음
    /*public void SameFunc()
    {
      Console.WriteLine("SameFunc");
    }*/
  }
}

partial struct와 partial interface

partial interface ITest
{
  void Interface_Test();
}

partial interface ITest
{
  void Interface_Test2();
}

partial struct S1
{
  void Struct_Test() { }
}

partial struct S1
{
  void Struct_Test2() { }
}

partial 메서드

// Definition in file1.cs
partial void OnNameChanged();

// Implementation in file2.cs
partial void OnNameChanged()
{
  // method body
}
  • C++ 같이 정의 및 선언의 구분이 가능하다

출처

카테고리: ,

업데이트: