유니티로 배우는 c#

형식 매개 변수 T

테오구 2021. 10. 10. 21:01
728x90
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class NewBehaviourScript : MonoBehaviour
{
    void Print<T>(T value) where T : class{//class타입만 허용합니다. 가령 float타입 같은 경우는 struct이기 때문에 오류가 뜹니다.
        print(value);

    }

    // Start is called before the first frame update
    void Start()
    {
        // Print('a'); // string이기 때문에 void Print(string value)에 들어간다.
        Print<string>("abc");
        Print<float>(4.3f);
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

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

public class Abc<T>
{
    // 어떤 타입이 올지 모를 때 사용
    public T var;
    public T[] array;
}

public class NewBehaviourScript1 : MonoBehaviour
{

    Abc<string> a;
    Abc<float> b;

    // Start is called before the first frame update
    void Start()
    {
        a.var = "abc";
        b.var = 4.5f;
        a.array = new string[1];
        b.array = new string[1];

        a.array[0] = "abc";
        b.array[0] = 4.5f;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
728x90

'유니티로 배우는 c#' 카테고리의 다른 글

Action과 Func  (0) 2021.10.11
람다식  (0) 2021.10.11
인터페이스  (0) 2021.10.10
인덱서  (0) 2021.10.10
프로퍼티  (0) 2021.10.10