프로퍼티(Property)에 대해 알아보자
프로퍼티에 대해 알아보자.
##
프로퍼티란?
객체의 데이터를 안전하게 읽고(Get) 수정(Set)하기 위한 C#의 기능.
변수(Field)를 직접 공개하지 않고 대신 사용하는 창구 라고 생각해보자
먼저 변수가 있다고 가정하자
class Person
{
public string name;
public int age;
}
이것을 사용한다고 하면
Person person = new Person();
person.name = "Ysw1mst";
person.age = 30;
Console.WriteLine(person.name);
Console.WriteLine(person.age);
Ysw1mst
이제 취약점을 생각해보자.
누군가가
person.name = "";
person.name = null;
person.name = "dog";
person.age = -100;
검사해서 막으면 되지 않을까?
if(person.age < 0)
{
}
이런식으로 검사하면 물론 되긴 하지만, 좋은코드는 아니다 100개의 객체가 있다고하면 100번을 검사해야한다. 한번이라도 실수한다면 잘못된코드, 프로그램이 되기 마련이다.
그래서 등장한것이 Property이다.
데이터를 직접 건드리지 않으며 Property를 통해서만 접근할 수 있게 한다.
일종의 검문소라고 생각하면 편하다.
private int age;
public int Age
{
get
{
return age;
}
set
{
if(value >= 0)
{
age = value;
}
}
}
age를 private변수로 선언하여 직접 접근할 수 없으며 프로퍼티를 통해서만 값을 Set(변화) 할 수 있다.
Field와 Property의 차이
Field
일반 변수
public int age;
Property
검문소 : 변수를 관리하는 기능
public int Age
{
get;
set;
}
예제
1. 프로퍼티 없이
namespace PropertyStudy;
class Person
{
public int Age;
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Age = 25;
Console.WriteLine(person.Age);
person.Age = -100;
Console.WriteLine(person.Age);
}
}
25
-100
2. 프로퍼티 사용
namespace PropertyPRC;
class Person
{
private int age;
public int Age
{
get
{
return age;
}
set
{
if (value >= 0)
{
age = value;
}
else
{
Console.WriteLine("You are not a person.");
}
}
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Age = 25;
Console.WriteLine(person.Age);
person.Age = -100;
Console.WriteLine(person.Age);
}
}
프로퍼티에서 value의 값이 0 이상이라면 age에 value값을 주입한다.
0보다 작다면 You are not a person을 출력하게 된다.
Program Class에서
person이라는 Person객체를 만들고
Age에 25를 주입한다 이때 Age는 25가 들어있게되고 그대로 Age를 출력한다.
이후 Age에 -100을 주입하려하지만 프로퍼티 조건에 의해 값은 주입되지않고 그대로 25가 유지되며
You are not a person을 출력한 후
원래 Age값인 25를 한번 더 출력하게 된다.
댓글
GitHub 계정으로 의견을 남길 수 있습니다.
GitHub에서 댓글 삭제