Unity C# 인터페이스 Interface

Intro

C# 인터페이스

인터페이스

인터페이스는 추상클래스와 비슷하지만 인스턴스를 가질수 없고 다중상속이 가능하여 클래스가 상속받아 사용하는 뼈대같은 개념이다.

인터페이스는 메소드, 프로퍼티, 인덱서, 이벤트 를 가질 수 있으며 선언만 가능하다.

인터페이스 활용 예시

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public delegate void EventHandler();

abstract public class A : MonoBehaviour
{
    abstract public void Abc();

}

interface IMethod // 인터페이스 메소드
{
    void Bbc();
}

interface IProperty // 인터페이스 프로퍼티
{
    int salaryP { get; set; }
}

interface IIndexer // 인터페이스 인덱서
{
   int this[int index]
    {
        get;
        set;
    }
}

interface IEvent // 인터페이스 이벤트
{
    event EventHandler OnDie;
}

public class Interface : A, IMethod, IProperty, IIndexer, IEvent
{
    private int[] arr = new int[100];
    private int salary;

    public event EventHandler OnDie; // 인터페이스 이벤트 구현

    public int salaryP // 인터페이스 프로퍼티 구현
    {
        get
        {
            return salary;
        }
        set
        {
            salary = value;
        }
    }

    public int this[int index] // 인터페이스 인덱서 구현
    {
        get
        {
            return arr[index];
        }
        set
        {
            arr[index] = value;
        }
    }

   

    public override void Abc() // 추상클래스 구현
    {
        print("Abc");
    }

    public void Bbc()  // 메소드 인터페이스 구현
    {
        print("Bbc");
    }

    private void EndGame() 
    {
        print("Game End");
    }
   
    void Start()
    {
        Abc();
        Bbc();

        salaryP = 10;
        print(salaryP);

        this[5] = 20;
        print(this[5]);


        OnDie += EndGame;

        OnDie();
    }


}

인터페이스를 이용하면 위와같이 뼈대를 만들어놓고 클래스에 상속시켜 활용할 수 있다.

또한 인터페이스가 인터페이스를 상속받아 인터페이스를 상속받은 인터페이스만 클래스에 상속시켜 사용하는것도 가능하다.

실행 결과

1

참고자료

https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/keywords/interface

https://youtu.be/Qh5rsovofPI?list=PLUZ5gNInsv_O7XRpaNQIC9D5uhMZmTYAf

태그: ,

카테고리:

업데이트:

댓글남기기