27
2017
09

C#泛型方法的反射

核心的方法就是method.MakeGenericMethod(genericType)

using System.Collections;
using System.Reflection;
using UnityEditor;
using System;
using UnityEngine;

public class TestGenericRlection
{
    [MenuItem ("Assets/TestGenericRlection")]
    static void Start ()
    {
        Main ();
    }


    public static void Foo<T> (T item)
    {
        Debug.LogFormat ("{0}: {1}", typeof(T), item);
    }

    static void CallByReflection (string name, Type typeArg, object value)
    {
        // Just for simplicity, assume it's public etc
        MethodInfo method = typeof(TestGenericRlection).GetMethod (name);
        MethodInfo generic = method.MakeGenericMethod (typeArg);
        generic.Invoke (null, new object[] { value });
    }

    static void Main ()
    {
        CallByReflection ("Foo", typeof(object), "actually a string");
        CallByReflection ("Foo", typeof(string), "still a string");
        // This would throw an exception
        // CallByReflection("Foo", typeof(int), "oops");
    }
}
上一篇:Android圆环选择View 下一篇:图片处理框架