Get user-created methods

8

I have a method that lists the methods that a given object has, I want to take only the methods created by the user, in this case: Add and Subtract

What this method returns me:

GenericClass

publicclassGenerico{publicobjectObjeto{get;set;}publicstring[]ListarMetodos(){varm=Objeto.GetType().GetMethods();string[]metodos=newstring[m.Length];for(inti=0;i<m.Length;i++)metodos[i]=String.Concat(i," [+] ", m[i].Name, "\n");
        return metodos;
    }
}

Example Class

public class Calculadora
{
    public int x { get; set; }
    public int y { get; set; }

    public Calculadora() { }

    public int Somar()
    {
        return this.x + this.y;
    }

    public int Subtrair()
    {
        return this.x - this.y;
    }
}
    
asked by anonymous 07.05.2014 / 22:43

2 answers

4

Use:

var m = Objeto.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).Where(x => !x.IsSpecialName).ToArray();
    
07.05.2014 / 22:58
5

You can check which type is the method declaration by using the DeclaringType property of MethodInfo , so you can filter the way you like:

public string[] ListarMetodos()
{
    var t = Objeto.GetType();
    return t.GetMethods()
        .Where(mi => mi.DeclaringType == t)
        .Where(x => !x.IsSpecialName)
        .Select((mi, i) => i + " [+] " + mi.Name)
        .ToArray();
}
    
07.05.2014 / 23:05