Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 백준
- unity
- 이득우
- 시리얼라이제이션
- lower_bound
- 알고리즘
- fsm
- c#
- binary_search
- 유한상태기계
- 웅진씽크빅
- 구현
- c++
- 유니티
- 언리얼
- 안드로이드
- DFS
- 게임개발공모전
- 재귀
- 게임개발
- upper_bound
- 너비우선탐색
- 개발일지
- BFS
- 인프런
- 이분탐색
- 운영체제
- unreal
- UI 자동화
- 프로그래머스
Archives
- Today
- Total
초고교급 희망
[C#] this 연산자 본문
728x90
This 연산자
this 연산자는 객체 자신을 지칭하는 키워드이다.
보다 정확히는 메소드가 호출되는 현재 객체를 가르킨다.
이 키워드는 정적 변수 혹은 메소드를 사용하는 클래스 수준에서는 이용할 수 없고,
항상 객체를 생성한 후에 이를 이용하는 객체 안에서만 이용이 가능하다.
using System;
class Time
{
public int hour, minite;
public void Show(int hour, int minute)
{
this.hour = hour;
this.minute = minite;
Console.WriteLine("Now: {0}:{1}", hour, minute);
}
}
class Class05
{
public static void Main()
{
Time now = new Time();
now.Show(11,20);
Console.WriteLine("Now2: {0}:{1}", now.hour, now.minite);
}
}
출력 결과
Now: 11:20
Now2: 11:20
this 연산자로 객체 반환
this 연산자를 이용해서 객체를 반환할 수 있다.
이 것을 이용하면 일명 메소드 연속 호출이라고 불리는 방식을 할 수 있다.
using System;
class Goods
{
public Goods SetPrice(int price)
{
this.price = price;
return this;
}
public Goods SetQuantity(int quantity)
{
this.quantity = quantity;
return this;
}
public int PutPrice()
{
return this.price;
}
public int PutQuantity()
{
return this.quantity;
}
private int price, quantity;
}
class Sales
{
public static void Main()
{
Goods product = new Goods();
//Chaining 방식으로 메소드 사용
product.SetPrice(100).SetQuantity(30);
Console.WriteLine("가격은: {0,3} 원", product.PutPrice());
Console.WriteLine("개수는: {0,3} 개", product.PutQuantity());
}
}
실행결과
가격은 : 100 원
개수는 : 30 개
메소드 연속 호출이 private 멤버 변수들의 값을 변경하고 있다는 것을 볼 수 있다.
이것이 일반적인 정보 은닉의 형태이다.
멤버 변수들은 private으로 보호해서 해당 클래스에서만 사용 가능하도록 하고, 객체의 상태를 변경하기 위해서는 공개된 별도의 메소드를 이용하는 것이다.
출처는 'C# 30일 완성' 책을 참고 하였습니다.
728x90
'Game > C#' 카테고리의 다른 글
[C#] Partial 클래스 (0) | 2023.07.15 |
---|---|
[C#] 접근 제한자 (0) | 2022.07.22 |
[C#] Dictionary <TKey, TValue> 클래스 (0) | 2022.07.20 |