* 인터페이스
interface 인터페이스명 {
void 메소드();
}
- 선언 가능 : 메소드, 이벤트, 인덱서, 프로퍼티
- 한정자 : public만 가능함. protected, private (x)
- 접근방법 : 인터페이스의 인스턴스는 생성 불가능함. 인터페이스를 상속받은 클래스의 인스턴스로 접근
* 인터페이스 상속
interface aaa{
void bbb();
}
class ccc : aaa{
aaa a = new ccc(); // 기반 클래스 = new 파생 클래스() 형태 같음.
a.bbb();
}
// 인터페이스도 클래스라고 생각하고 접근하면 됨
* 인터페이스 상속 관련
interface Iinter
{
void writelog(string mes);
}
class filelogger : Iinter
{
private StreamWriter write;
public filelogger(string path)
{
write = File.CreateText(path);
write.AutoFlush = true;
}
public void writelog(string mes)
{
write.WriteLine("{0} {1}", DateTime.Now.ToShortDateString(), mes);
}
}
class climate
{
private Iinter inter;
public climate(Iinter inter)
{
this.inter = inter;
}
public void start()
{
while (true)
{
Console.WriteLine("온도");
string temp = Console.ReadLine();
if (temp == "")
{
break;
}
inter.writelog("온도: " + temp);
}
}
}
class Program
{
static void Main(string[] args)
{
climate mon = new climate(new filelogger("mylog.txt"));
mon.start();
}
}
// 온도를 메모장에 찍어내는 소스코드다.
// 처음에 파라미터로 넘겨준건 Iinter inter = new filelogger()로 보면 됨 (기반 = new 파생)
// inter.writelog은 인터페이스로 가지않고 파생 클래스로 가서 실행
* LOG 찍는 방법
1. system.io // namespace 선언
2. private StreamWriter log; // 변수 선언
3. log = File.CreateText("abc.txt"); // 경로설정
4. log.WriteLine("찍을 내용“);
5. log.AutoFlush = true; // 컴터 내 저장한 버퍼 비우고 txt에 저장하는 걸 말함
* 다중 상속
interface IRunnable
{
void Run();
}
interface IFlyable
{
void Fly();
}
class FlyingCar : IRunnable, IFlyable
{
public void Run()
{
Console.WriteLine("Run! Run!");
}
public void Fly()
{
Console.WriteLine("Fly! Fly!");
}
}
class MainApp
{
static void Main(string[] args)
{
FlyingCar car = new FlyingCar(); // 파생에서 메소드 접근
car.Run();
car.Fly();
IRunnable runnable = car as IRunnable; // 기반에서 메소드 접근
runnable.Run(); // 인터페이스를 뽑았지만 파생에서 출력
IFlyable flyable = car as IFlyable;
flyable.Fly();
}
}
// 하나의 클래스에 두 개의 인터페이스를 받음
// 메소드는 파생으로 직접 접근해도 되고 인터페이스로 접근해도 됨