읽기 전용 및 쓰기 전용 프로퍼티
Coddy C# 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 70개 중 11번째.
때로는 읽기만 하거나 쓰기만 할 수 있는 property가 필요합니다. 개별 접근자에 private를 사용하여 이를 제어할 수 있습니다.
읽기 전용 property에는 public getter가 있지만 private setter가 있거나 setter가 전혀 없습니다:
public class User
{
public string Username { get; private set; }
public User(string username)
{
Username = username;
}
}외부 코드는 Username을 읽을 수 있지만, only class 자체만 이를 수정할 수 있습니다. 이는 생성 중에 한 번만 설정해야 하는 값에 유용합니다.
쓰기 전용 property에는 public setter가 있지만 private getter가 있습니다:
public class Account
{
public string Password { private get; set; }
public bool ValidatePassword(string input)
{
return input == Password;
}
}쓰기 전용 property는 드물지만, stored 값을 노출하지 않고 input을 accepts하려는 password와 같은 민감한 데이터에 유용합니다.
getter만 사용하여 진정한 읽기 전용 property도 만들 수 있습니다.
public class Circle
{
public double Radius { get; }
public double Area => Math.PI * Radius * Radius;
public Circle(double radius)
{
Radius = radius;
}
}get;만 있는 property는 constructor 또는 선언 시에만 할당할 수 있으므로, object 생성 후에는 불변입니다.
챌린지
쉬움민감한 데이터를 보호하기 위해 read-only 및 write-only property를 언제 사용해야 하는지 보여 주는 안전한 configuration system을 만들어 보겠습니다.
코드를 구성하기 위해 두 개의 파일을 만듭니다:
Config.cs:Settingsnamespace에 서버 configuration을 관리하는ServerConfigclass를 정의합니다. 다음을 포함해야 합니다:- read-only property
ServerName(constructor에서만 설정 가능) - private setter가 있는 read-only property
Port(constructor를 통해 설정) - secret key를 internally 저장하는 write-only property
ApiKey - 제공된 key가 stored key와 일치하면
true를 returns하는 methodValidateApiKey(string key) - server name과 port를 accepts하는 constructor
- read-only property
Program.cs: main file에서 input 값을 사용해ServerConfigobject를 만들고, API key를 설정한 다음 test key와 비교하여 검증합니다.
네 개의 input을 받습니다:
- Server name
- Port number
- 저장할 API key
- 검증할 API key
server 세부 정보와 검증 결과를 다음 Format으로 print합니다:
Server: {ServerName}, Port: {Port}
API Key Valid: {True/False}예를 들어 input이 MainServer, 8080, secret123, secret123인 경우 output은 다음과 같아야 합니다:
Server: MainServer, Port: 8080
API Key Valid: True직접 해보기
using System;
using Settings;
class Program
{
public static void Main(string[] args)
{
// 입력 읽기
string serverName = Console.ReadLine();
int port = Convert.ToInt32(Console.ReadLine());
string apiKeyToStore = Console.ReadLine();
string apiKeyToValidate = Console.ReadLine();
// TODO: serverName과 port로 ServerConfig 객체 생성
// TODO: 쓰기 전용 속성을 사용하여 API 키 설정
// TODO: API 키를 검증하고 결과 출력
// 형식: Server: {ServerName}, Port: {Port}
// API Key Valid: {True/False}
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러