1. 程式人生 > >Unity--泛型函式呼叫

Unity--泛型函式呼叫

using UnityEngine;

public abstract class Animal
{
    public abstract void Walk(int step);
}

public class Dog : Animal
{
    public override void Walk(int step)
    {
        Debug.Log(string.Format("Dog Walk {0} step", step));
    }
}

public class Bird : Animal
{
    public override void Walk(int step)
    {
        Debug.Log(string.Format("Bird Walk {0} step", step));
    }
}

public class TestClass
{
    public void DoWalk<T>(int step) where T : Animal, new()
    {
        var t = new T();
        t.Walk(step);
    }

    public static void DoWalk2<T>(int step) where T : Animal, new()
    {
        var t = new T();
        t.Walk(step);
    }
}

public class GenericMethodTest : MonoBehaviour
{
    void Start()
    {
        int step = 5;

        //呼叫非static泛型函式
        TestClass obj = new TestClass();
        var methodInfo = obj.GetType().GetMethod("DoWalk");
        Debug.Log("泛型方法定義:" + methodInfo.IsGenericMethodDefinition);
        var mi = methodInfo.MakeGenericMethod(typeof(Dog));
        mi.Invoke(obj, new object[] { step });

        //呼叫static泛型函式
        var methodInfo2 = typeof(TestClass).GetMethod("DoWalk2");
        var mi2 = methodInfo2.MakeGenericMethod(typeof(Bird));
        mi2.Invoke(null, new object[] { step });
    }
}