【问题标题】:c# - How to set the correct order of the parameters invoking with reflection?c# - 如何设置通过反射调用的参数的正确顺序?
【发布时间】:2017-12-26 20:49:13
【问题描述】:

我需要从任何类(在同一个程序集中)调用任何方法并传递参数。到目前为止一切顺利(我相信),但 Invoke 要求我提供一个对象数组(我可以获得),但顺序与方法中预定义的顺序相同。

我为参数做了这个类:

public  class Parametros {
    public string type { get; set; }
    public string name { get; set; }
    public object value { get; set; }

}

我的“调用”方法如下:

    public static void Executar(string namespaceClass, string metodo,List<Parametros> parametros) {
        Type type = Type.GetType(namespaceClass);
        Object obj = Activator.CreateInstance(type);
        MethodInfo methodInfo = type.GetMethod(metodo);
        List<object> myParams = new List<object>();
        foreach (Parametros myparam in parametros) {
            //Get and order the params
            myParams.Add(myparam.value);
        }

        methodInfo.Invoke(obj, myParams.ToArray());
    }

如果没有在我的类Parametros中指定顺序的解决方案,有什么办法可以做到这一点,获取参数的名称并将其发送给invoke方法?

【问题讨论】:

    标签: c# .net reflection invoke delegation


    【解决方案1】:

    终于我明白了,我会把答案告诉任何需要它的人。它适用于静态和非静态类型。考虑到 namespaceClass 必须是Namespace.etc.Class

        public static void Executar(string namespaceClass, string metodo, List<Parametros> parametros = null)
        {
            Type type = Type.GetType(namespaceClass);
            MethodInfo methodInfo = type.GetMethod(metodo);
            Object objectToInvoke;
            if (type.IsAbstract && type.IsSealed)
            {
                objectToInvoke = type;
            }
            else {
                objectToInvoke = Activator.CreateInstance(type);
            }
    
            ParameterInfo[] parametersFromMethod = methodInfo.GetParameters();
    
    
    
            if (parametros != null || (methodInfo != null && parametersFromMethod != null && parametersFromMethod.Length > 0))
            {
                List<object> myParams = new List<object>();
                foreach (ParameterInfo parameterFound in parametersFromMethod)
                {
                    Parametros parametroEspecificado = parametros.Where(p => p.name == parameterFound.Name).FirstOrDefault();
                    if (parametroEspecificado != null)
                    {
                        myParams.Add(parametroEspecificado.value);
                    }
                    else
                    {
                        myParams.Add(null);
                    }
    
                }
    
                methodInfo.Invoke(objectToInvoke, myParams.ToArray());
    
            }
            else
            {
                methodInfo.Invoke(objectToInvoke, null);
            }
    
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多