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(int step) where T : Animal, new()
    {
        var t = new T();
        t.Walk(step);
    }

    public static void DoWalk2(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 });
    }
}

你可能感兴趣的:(Unity,unity,泛型,函数,invoke,generic)