C# get set 프로퍼티 예제 및 필요성
페이지 정보
작성자 sbLAB 댓글 0건 조회 5,302회 작성일 18-07-25 18:04본문
propfull -> TAB -> TAB
1 .프로퍼티는 그 클래스 내부 변수를 private 로 보호하고 캡슐화 한다.
2. 프로퍼티는 프로퍼티 접근 메서드를 이용해 대입 변수에 대한 적절한 대응이 가능하도록 한다.
[프러퍼티 기본예제]
using System;
using System.Text;
namespace getset
{
public class Student
{
private string _name;
public void SetName(string name)
{
this._name = name;
}
public string GetName()
{
return string.IsNullOrEmpty(this._name) ? "No name" : this._name;
}
}
class Program
{
static void Main(string[] args)
{
Student sd = new Student();
sd.SetName("");
Console.WriteLine(sd.GetName());
sd.SetName("Brus");
Console.WriteLine(sd.GetName());
}
}
}
[get / set 을 이용하면서 프로퍼티 변수에 대해 조건검증]
using System;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SP spTest = new SP(0, 0);
int xTest = spTest.X;//spTest.X.get 호출
int yTest = spTest.Y;//spTest.Y.get 호출
spTest.X = 40;// 값을 40으로 설정하기위해 spTest.X.set호출
spTest.Y = 100;
Console.WriteLine(spTest.X);
Console.ReadKey();
}
}
class SP
{
//private
private int x, y;
//constructor
public SP(int x, int y)
{
this.x = ckRangX(x);
this.y = ckRangY(y);
}
//-------------------------------------------------------------------
//구분 : 함수
//Name : ckRangX
//인자 : x - 범위검사할 숫자
//설명 : 0< x < 1280 사이값이 아니라면 예외 던지기
//-------------------------------------------------------------------
private static int ckRangX(int x)
{
if (x < 0 || x > 1280)
{
throw new ArgumentOutOfRangeException("X");
}
return x;
}
//-------------------------------------------------------------------
//구분 : 함수
//Name : ckRangY
//인자 : y - 범위검사할 숫자
//설명 : 0< y < 1280 사이값이 아니라면 예외 던지기
//-------------------------------------------------------------------
private static int ckRangY(int y)
{
if (y < 0 || y > 1280)
{
throw new ArgumentOutOfRangeException("Y");
}
return y;
}
//속성 X
public int X
{
get { return this.x; }
set { this.x = ckRangX(value); }
}
//속성 Y
public int Y
{
get { return this.y; }
set { this.y = ckRangY(value); }
}
}
}
댓글목록
등록된 댓글이 없습니다.