글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
오늘 소개해 드리는 토픽은 다음과 같습니다.
Automatically Implemented Properties - Visual Studio Orcas C# Compiler - C# 3.0
; http://davidhayden.com/blog/dave/archive/2006/12/07/AutomaticallyImplementedPropertiesCSharpCompiler.aspx
그 전에 다음의 토픽을 봐두시는 것도 좋을 듯 싶습니다. ^^
프로퍼티와 공용 필드에 대한 선택
; https://www.sysnet.pe.kr/2/2/93
정리해 보면, 예전 같으면 다음과 같이 선언하던 것을,
private string name;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
이제는 C# 3.0 컴파일러의 지원으로 다음과 같이 줄여서 쓰는 것이 가능해 졌습니다.
public string Name { get; set; }
Access Modifier가 온다는 것만 제외한다면 인터페이스에서의 속성 선언하는 구문과 동일하다는 것을 알 수 있습니다. 조금 다른 점이 있다면, 반드시 get; set; 을 모두 포함하고 있어야 합니다. (업데이트 2021-01-27: C# 6.0부터 set을 제거한 readonly 표현이 가능해졌습니다.)
사용예는 다음과 같습니다.
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConsoleApplication1
{
public class Customer
{
public string Test { get; set; } // C# 3.0
public int Age { get; } // C# 6.0
public bool HasJob { get; } = true; // C# 6.0
public void DoFunc()
{
this.Test = "TEST";
}
public Customer()
{
Age = 10; // read-only 속성은 생성자 내에서만 변경 가능
}
}
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.Test = "Test";
}
}
}
.NET Reflector 로 열어봤더니 다음과 같이 되어 있는 것을 확인할 수 있었습니다.
[CompilerGenerated]
private string <>k__AutomaticallyGeneratedPropertyField0;
public string Test
{
[CompilerGenerated]
get
{
return this.<>k__AutomaticallyGeneratedPropertyField0;
}
[CompilerGenerated]
set
{
this.<>k__AutomaticallyGeneratedPropertyField0 = value;
}
}
낯이 익은 트릭이죠? 익명 메서드를 처리하던 것과 유사한 방식으로... 중복되지 않을 듯한 이름으로 된 내부 private 필드를 정의해 놓고 그것을 사용하고 있습니다.
[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]
[연관 글]
... 196 [197]
... 196 [197]