C# 강좌 : 제 14강 - 클래스 & 메서드 (2)
클래스 파일(Class File)
자주 사용되거나 프로그램이 커질수록 코드를 한눈에 알아보기가 매우 어려워집니다.
이를 해결하기 위해서 cs파일
을 추가하여 가독성
, 확장성
, 재사용성
등을 높일 수 있습니다.
항목 추가
프로젝트(P) → 클래스 추가(C)
또는 프로젝트(P) → 새 항목 추가(W)
를 눌러 클래스를 추가합니다.
클래스
를 선택하고 이름을 animal.cs
로 변경하고 추가합니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class animal
{
}
}
새로운 cs창이 뜨게되며 여러다른 Form
에서도 불러와 사용할 수 있습니다.
이 새로운 클래스 창에서도 본래의 Form1
처럼 사용이 가능한데, 사용할 namespace
를 using
란에 추가시켜주면 가능합니다.
- Tip : 클래스에서
MessageBox
를 사용하려면using System.Windows.Forms;
키워드를 상단에 추가시키면 됩니다.
프로젝트 구성
도구상자에서 GroupBox
, VScrollBar
, Label
을 Form1
에 생성합니다.
위 이미지와 같이 배치합니다.
속성을 다음과 같이 설정합니다.
- GroupBox
- Text : 몸무게
- VScrollBar
- LargeChange : 1
- Maximum : 30
- Value : 30
- Label (1번)
- Text : 0kg
- Label (2번)
- Text : 크기 : -
- Font : 크기 28
animal.cs 코드창을 열어 아래와 같이 입력합니다.
세부 코드
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class animal
{
public string size(int weight)
{
if (weight > 20) return "대형";
else if (weight > 10) return "중형";
else return "소형";
}
}
}
외부에서 weight
라는 값을 받아 비교하여 string(문자열)값
으로 반환하는 형식의 코드입니다.
weight
가 20보다 크면 대형, 10보다 크면 중형, 위의 조건에 만족하지 않는 경우 소형으로 반환
합니다.
vScrollBar1
를 더블클릭하여 이벤트
를 활성화시키고 아래와 같이 입력합니다.
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
int weight = vScrollBar1.Maximum - vScrollBar1.Value;
label1.Text = weight + "kg";
animal ani = new animal();
label2.Text = "크기 : " + ani.size(weight);
}
weight
라는 변수를 vScrollBar
의 값을 받아와 적용시키는것을 알 수 있습니다.
여기서 Maximum
값을 빼주는 이유는 상단이 최고점, 하단이 최하점으로 위치를 바꿔주기 위해서입니다.
label1에 몸무게를 표시하고, animal
의 클래스를 ani
로 불러온 후, ani.size(weight)
를 통하여 계산 후, 바로 표시합니다.
클래스를 이용하여 메인 폼
의 코드량이 매우 줄어들며, 가독성이 늘어나고 재사용성을 키우는 것을 한 눈에 확인 할 수 있습니다.
전체 코드
Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
int weight = vScrollBar1.Maximum - vScrollBar1.Value;
label1.Text = weight + "kg";
animal ani = new animal();
label2.Text = "크기 : " + ani.size(weight);
}
}
}
animal.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class animal
{
public string size(int weight)
{
if (weight > 20) return "대형";
else if (weight > 10) return "중형";
else return "소형";
}
}
}
공유하기


댓글 남기기