jeudi 28 mai 2015

Make Func<> for a generic type

I have this architecture.

public void Init()
    {
        PropertyInfo[] infos = typeof(Transform).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo info in infos)
        {
            // Save getter
            MethodInfo method = info.GetGetMethod();
            System.Type returnType = method.ReturnType;


            System.Func<Transform, Vector3> fact = GetFactory<Transform, Vector3>(method);

            Vector3 v = fact(this.Value);
            Debug.Log("Test123 " + v);

            //_getters.Add(info.Name, newMethod);
        }
    }

    static System.Func<T, T1> GetFactory<T, T1>(MethodInfo info)
    {
        return (System.Func<T, T1>)GetFactory(typeof(T), typeof(T1), info);
    }

    static object GetFactory(System.Type type, System.Type type1, MethodInfo info)
    {
        System.Type funcType = typeof(System.Func<,>).MakeGenericType(type, type1);
        return System.Delegate.CreateDelegate(funcType, info);
    }

It even works if method.ReturnType is Vector3. But I want the func<Transform, Vector3> to be func<Transform, ReturnType>. I have no idea doing this.

Does someone of you know how I can do this?

And I also have no idea how to save the result in a dictionary. Which type can the dictionary be of?

 public Dictionary<string, System.Func<object, object>> _getters = new Dictionary<string, System.Func<object, object>>();

Illustration





Aucun commentaire:

Enregistrer un commentaire