Check for function existence in C #

1

How can I check if a function exists in C# ? I think I have to use some kind of reflection, but I do not know much about it. Is there a way to get the function's argument list, if it exists?

For example:

public class ClasseA {

public bool Funcao1(string a, string b){       

    //Código da função
}

public bool Funcao2(string a, string b){
    //Código da função
}

public bool Funcao10(string a, string b) {
   //Código da função
}

public bool VerificaExistenciaFuncoes(){
{
       bool bTodasExistem = true;
       for(int i = 1; i<=10;i++){

         // Aqui quero fazer algo do tipo:
         // Se função não existe "Funcao" + i -> bTodasExistem = false;
      }              

    return bTodasExistem;

}

}
    
asked by anonymous 03.04.2017 / 16:39

3 answers

2
  

I do not see a sense in doing this. As was said in the comments, C # is not a dynamic language that the function may or may not exist. However, I will respond anyway.

As you said in the question, you can use Reflection to check whether or not the method exists in the object. A simple example would be this:

using System;

public class Program
{
    public static void Main()
    {
        var classeA = new ClasseA();
        var existeFuncoes = VerificaExistenciaFuncoes(classeA, "Funcao");
        Console.WriteLine(existeFuncoes);

    }
    public static bool VerificaExistenciaFuncoes(object obj, string prefixMethod)
    {
        var type = obj.GetType();
        bool bTodasExistem = true;
        for (int i = 1; i <= 10; i++)
        {
            var function = type.GetMethod(prefixMethod + i);
            //estou percorrendo o laço todo, mas poderia retornar false de uma vez
            if (function == null)
                bTodasExistem = false;
        }

        return bTodasExistem;
    }
}


public class ClasseA
{

    public bool Funcao1(string a, string b)
    {
        return true;
    }

    public bool Funcao2(string a, string b)
    {
        return true;
    }

    public bool Funcao10(string a, string b)
    {
        return true;
    }
}

Note that I have separated the VerificaExistenciaFuncoes() method from classeA and put 2 parameters for it, obj and prefixmethod .

Obj is nothing more than the object you are checking whether the method exists or not.

prefixMethod is the prefix of the function you want to check. Since what will change in your example is just the number, I've put this parameter to make it easier to explain.

Now, to verify whether or not the method exists, just use Type.GetMethod () , passing the name of the method you want to check.

See working in DotNetFiddle.

    
03.04.2017 / 20:59
2

Here is an example of how to get the methods and their list of parameters:

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Teste
{
    public class Program
    {
        public static void Main(string[] args)
        {            
            Teste t = new Teste();
            //Pega todas as informações dos metodos a partir do tipo do objeto (classe), você pode informar através das flags um filtro (publico, privado)
            MethodInfo[] methodInfos = Type.GetType(t.GetType().ToString()) 
                           .GetMethods(BindingFlags.Public | BindingFlags.Instance);

            foreach (MethodInfo method in methodInfos)
            {
                //Mostra o nome do metodo
                System.Console.WriteLine(method.Name);
                //Pega todos os parametros do metodo
                foreach(ParameterInfo parameter in method.GetParameters())
                {
                    //Posição do parametro
                    int pos = parameter.Position;
                    //Nome do tipo do parametro (int, string)
                    string nameOfType = parameter.ParameterType.Name;
                    //Nome do parametro
                    string nameOfParam = parameter.Name;
                    System.Console.WriteLine(pos);
                    System.Console.WriteLine(nameOfType);
                    System.Console.WriteLine(nameOfParam);
                }
            }
        }
    }

    public class Teste
    {
        public void meuMetodo(string arg1, string arg2)
        {

        }

        public int meuMetodo2(int arg1, int arg2)
        {
            return 1;
        }
    }
}

References:

I hope I have helped.

    
03.04.2017 / 21:19
0

There is, and is already answered in English here link

More accurate answer in English and translated:

  

You can solve the Type from a string by using the Type.GetType (String)> method. For example:

     

To solve a class from a String you can use the function Type.GetType (String)

Type myType = Type.GetType("MyNamespace.MyClass");

  

You can then use this Type instance to check if a method exists on the> type by calling the GetMethod (String) method. For example:

     

From the class, you can validate the existence of a function through the GetMethod (String) function. For example:

MethodInfo myMethod = myType.GetMethod("MyMethod");

  Both GetType and GetMethod return null if no type or method was found for the given name, so you can check if your type / method exists by checking if your method returned null or not.

     

Both the GetType and GetMethod function will return null case for the provided String, there is no class or function respectively.

     

Finally, you can instantiate your type using> Activator.CreateInstance (Type) For example:

     

Finally, from the data obtained, it is possible to instantiate an object of the class from the function Activator.CreateInstance (Type)

object instance = Activator.CreateInstance(myType);

For the second part of the question, to get the parameters, there is the function GetParameters () that belongs to the class MethodInfo.:

ParameterInfo[] pars = myMethod.GetParameters(); foreach (ParameterInfo p in pars) { Console.WriteLine(p.ParameterType); }

    
03.04.2017 / 17:09