회원 로그인
정보기억 정보기억에 체크할 경우 다음접속시 아이디와 패스워드를 입력하지 않으셔도 됩니다.
그러나, 개인PC가 아닐 경우 타인이 로그인할 수 있습니다.
PC를 여러사람이 사용하는 공공장소에서는 체크하지 마세요.
소셜네트워크 서비스를 통해서 로그인하시면 별도의 로그인 절차없이 회원서비스를 이용하실 수 있습니다.


최근 게시물

1.노션에서 작성 중

1.노션에서 작성 중

개편하기 전까지 노션에서 작성 중

2024.04.04//read more

2.ChatGPT

2.ChatGPT

OpenAI로 대규모 언어 모델대화형...

2023.03.16//read more

3.노코딩 게임 엔진 - 빌..

3.노코딩 게임 엔진 - 빌..

빌드 지원안드로이드iOS윈도우즈특이사...

2023.03.14//read more

4.(완료) 미접속 회원 정..

4.(완료) 미접속 회원 정..

[완료] 36명의 회원을 정리하였습니...

2023.02.16//read more

5.매뉴얼 플러스 - 전자제..



안정적인 DNS 서비스 DNSEver
DNS Powered by DNSEver.com


Generic (제네릭) (with Unity)

푸딩뱃살 | 2015.11.22 12:32 | 조회 4908
C# Generic (제네릭)

제네릭 타입 클래스를 정의하고 자료형을 맘대로 캐스팅할 수 있다.

예로 일반 적인 정수형 덧셈 클래스에서 정수형 매계 변수를 2개를 받아 덧셈을 수행해서 정수형으로 리턴한다. 정수형으로 정의된 클래스에선 다른 타입으로 실행할 수 없다.
이것을 제네릭으로 사용하여 다른 자료형으로 실행할 수 있게 된다.

C++에서는 Templete (템플릿) 사용
C#에선 Gerneric (제네릭) 사용

제네릭 클래스 예제
*유니티에서 Main Camera에 컴포넌트 추가하여 실행
using UnityEngine;
using System.Collections;

public class Monster
{
    private string _name;
    private int _damage;

    public Monster()
    {
        _name = "오크";
        _damage = 10;
    }

    public void Attack()
    {
        Debug.Log(_name + " 몬스터가 " + _damage + "로 공격을 합니다.");
    }
}

public class Weapon
{
    private int _str;
    private int _dex;
    private int _con;

    public Weapon()
    {
        _str = 80;
        _dex = 30;
        _con = 50;
    }

    public void ShowStat()
    {
        Debug.Log("힘 : " + _str + ", 민첩" + _dex + ", 체력 : " + _con);
    }
}

// [제네릭 클래스]
// public class 클리스명<T>
public class GenericContainer<T>
{
    private T _value;

    public void SetValue(T value)
    {
        _value = value;
    }

    public T GetValue()
    {
        return _value;
    }
}

public class GenericEx1 : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

        GenericContainer<Monster> gContain1 = new GenericContainer<Monster>();
        // Monster monster = new Monster();  // 일반
        // gContain1.SetValue(monster);  // 일반
        gContain1.SetValue(new Monster());  // 제네릭
        //Monster monster = gContain1.GetValue();  // 일반 
        //monster.Attack();  // 일반
        gContain1.GetValue().Attack();  // 제네릭

        GenericContainer<Weapon> gContain2 = new GenericContainer<Weapon>();
        gContain2.SetValue(new Weapon());
        gContain2.GetValue().ShowStat();

        GenericContainer<string> gContain3 = new GenericContainer<string>();
        gContain3.SetValue("+5 낭만의 셔츠 무료 증정!!!");
        Debug.Log("게임 소식 메시지 : " + gContain3.GetValue());

        GenericContainer<int> gContain4 = new GenericContainer<int>();
        gContain4.SetValue(123);
        Debug.Log("기본 자료형 데이타 : " + gContain4.GetValue());
    }
}

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

// 스택 클래스(Int형)
public class CStackInt
{
    int emptyStack;  // 빈스택 인덱스
    int[] items;  // int 아이템 배열
    int top;  // 현재 스택 커서(번호)
    int size;  // 스택 크기(아이템 저장 갯수)

    // 스택 객체 생성자
    public CStackInt(int size)
    {
        this.size = size;
        items = new int[size];
        emptyStack = -1;
        top = emptyStack;
    }

    public void Push(int item)
    {
        items[++top] = item;
    }

    public int Pop()
    {
        return items[top--];
    }

    public bool IsFull()
    {
        return (top + 1) == size;
    }

    public bool IsEmpty()
    {
        return top == emptyStack;
    }
}

// 스택 클래스(Float형)
public class CStackFloat
{
    int emptyStack;
    float[] items;  // float 아이템
    int top;
    int size;

    // 스택 객체 생성자
    public CStackFloat(int size)
    {
        this.size = size;
        items = new float[size];  // float 배열 생성
    }

    public void Push(float item)  // float 아이템 추가
    {
        items[++top] = item;
    }

    public float Pop()  // float 아이템 반환
    {
        return items[top--];
    }

    public bool IsFull()
    {
        return (top + 1) == size;
    }

    public bool IsEmpty()
    {
        return top == emptyStack;
    }
}

// 스택 클래스(String형)
public class CStackString
{
    int emptyStack;
    string[] items;  // float 아이템
    int top;
    int size;

    // 스택 객체 생성자
    public CStackString(int size)
    {
        this.size = size;
        items = new string[size]; // flaot 배열 생성
        emptyStack = -1;
        top = emptyStack;
    }

    public void Push(string item)  // float 아이템 추가
    {
        items[++top] = item;
    }

    public string Pop()  // float 아이템 반환
    {
        return items[top--];
    }

    public bool IsFull()
    {
        return (top + 1) == size;
    }

    public bool IsEmpty()
    {
        return top == emptyStack;
    }
}

public class CItem
{
    string itemName;

    public CItem(string itemName)
    {
        this.itemName = itemName;
    }

    public string GetItemName()
    {
        return itemName;
    }
}

// 스택 클래스(제네릭)
public class CStack<T>
{
    int emptyStack;
    T[] items;  // float 아이템
    int top;
    int size;

    // 스택 객체 생성자
    public CStack(int size)
    {
        this.size = size;
        items = new T[size];   // float 배열 생성
        emptyStack = -1;
        top = emptyStack;
    }

    public void Push(T item)   // float 아이템 추가
    {
        items[++top] = item;
    }

    public T Pop()  // flaot 아이템 반환
    {
        return items[top--];
    }

    public bool IsFull()
    {
        return (top + 1) == size;
    }

    public bool IsEmpty()
    {
        return top == emptyStack;
    }
}

public class CGenericBase : MonoBehaviour {

    void Start()
    {
        // 제네릭 사용하지 않았을때 스택을 사용하는 코드

        /*
        int size = 5;
        CStackInt istack = new CStackInt(size);

        for (int i = 0; i < 7; i++)
        {
            if (!istack.IsFull())
            {
                istack.Push(i);
            }
            else
            {
                Debug.Log("스택이 꽉 찼습니다. [저장 실패 : " + i + "]");
            }
        }

        while (!istack.IsEmpty())
        {
            Debug.Log(istack.Pop());
        }

        CStackFloat fstack = new CStackFloat(size);

        for (int i = 0; i < 7; i++)
        {
            if (!fstack.IsFull())
            {
                fstack.Push(i + 0.1f);
            }
            else
            {
                Debug.Log("스택이 꽉 찼습니다. [저장 실패 : " + i + "]");
            }
        }

        while (!fstack.IsEmpty())
        {
            Debug.Log(fstack.Pop());
        }

        CStackString sstack = new CStackString(size);

        for (int i = 0; i < 7; i++)
        {
            if (!sstack.IsFull())
            {
                sstack.Push(i.ToString());
            }
            else
            {
                Debug.Log("스택이 꽉 찼습니다. [저장 실패 : " + i + "]");
            }
        }

        while (!sstack.IsEmpty())
        {
            Debug.Log(sstack.Pop());
        }
        */

        // 제네릭을 사용했을때 스택을 사용하는 코드

        /*
        int size = 5;
        CStack<int> istack = new CStack<int>(size);

        for (int i = 0; i < 7; i++)
        {
            if (!istack.IsFull())
            {
                istack.Push(i);
            }
            else
            {
                Debug.Log("스택이 꽉 찼습니다. [저장 실패 : " + i + "]");
            }
        }

        while (!istack.IsEmpty())
        {
            Debug.Log(istack.Pop());
        }

        CStack<float> fstack = new CStack<float>(size);

        for (int i = 0; i < 7; i++)
        {
            if (!fstack.IsFull())
            {
                fstack.Push(i + 0.1f);
            }
            else
            {
                Debug.Log("스택이 꽉 찼습니다. [저장 실패 : " + i + "]");
            }
        }

        while (!fstack.IsEmpty())
        {
            Debug.Log(fstack.Pop());
        }

        CStack<string> sstack = new CStack<string>(size);

        for (int i = 0; i < 7; i++)
        {
            if (!sstack.IsFull())
            {
                sstack.Push(i.ToString());
            }
            else
            {
                Debug.Log("스택이 꽉 찼습니다. [저장 실패 : " + i + "]");
            }
        }

        while (!sstack.IsEmpty())
        {
            Debug.Log(sstack.Pop());
        }
        */

        // 제네릭 사용
        int size = 3;
        CStack<CItem> itemStack = new CStack<CItem>(size);

        itemStack.Push(new CItem("도적의검"));
        itemStack.Push(new CItem("백색 기사의 방패"));
        itemStack.Push(new CItem("견습사의 도검"));

        while (!itemStack.IsEmpty())
        {
            Debug.Log(itemStack.Pop().GetItemName());
        }
    }
}
285개(1/15페이지)
프로그래밍
번호 제목 글쓴이 조회 날짜
285 [Python] 동적 import - 모듈을 변수로 받아오기 푸딩뱃살 422 2022.10.27 10:45
284 [Python] 파이썬 3.7.7과 3.9.7의 os.path.expanduser() 차이 푸딩뱃살 466 2022.08.18 12:22
283 [Python] error: Microsoft Visual C++ 9.0 is required. 첨부파일 푸딩뱃살 701 2022.08.03 13:35
282 [Python] pyscript 첨부파일 푸딩뱃살 471 2022.06.09 11:21
281 [Python] float is / float not is 푸딩뱃살 604 2022.03.02 15:03
280 [Python] 이터널 문자열 f 푸딩뱃살 846 2022.01.27 16:35
279 [Python] is와 ==의 차이 푸딩뱃살 488 2021.11.25 15:54
278 [Python] Error: ImportError: file line 1: Ba 푸딩뱃살 940 2021.11.16 11:24
277 [Python] 파이썬 디컴파일 - uncompyle6 첨부파일 푸딩뱃살 786 2021.11.10 14:46
276 [Python] 파이썬 확장자 설명 푸딩뱃살 559 2021.11.03 14:38
275 [참고] 웹 fbx 뷰어 푸딩뱃살 477 2021.10.19 15:46
274 [Python] enumerate() 푸딩뱃살 506 2021.10.13 14:44
273 [Python] 아나콘다에서 가상 환경 첨부파일 푸딩뱃살 741 2020.11.21 00:26
272 [Python] pip로 설치 때 퍼미션 에러 사진 첨부파일 푸딩뱃살 1280 2020.06.06 17:13
271 [Python] OpenCV 10-3. 이미지 Thresholding - Otsu's Binarizatio 사진 푸딩뱃살 679 2020.06.05 14:01
270 [Python] OpenCV 10-2. 이미지 Thresholding - Adaptive Threshold 사진 푸딩뱃살 704 2020.06.05 13:58
269 [Python] OpenCV 10-1. 이미지 Thresholding 사진 푸딩뱃살 584 2020.06.05 13:56
268 [Python] OpenCV 9-2. 색 추적 푸딩뱃살 788 2020.06.02 23:29
267 [Python] OpenCV 9-1. 색공간 바꾸기 푸딩뱃살 645 2020.06.02 23:27
266 [Python] OpenCV 8-3. 이미지 비트 연산 사진 푸딩뱃살 536 2020.06.02 23:21