Get user-created methods

Asked

Viewed 129 times

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 to me: inserir a descrição da imagem aqui

Generic Class

public class Generico
{
    public object Objeto { get; set; }

    public string[] ListarMetodos()
    {
        var m = Objeto.GetType().GetMethods();
        string[] metodos = new string[m.Length];

        for (int i = 0; i < m.Length; i++)
            metodos[i] = String.Concat(i, " [+] ", m[i].Name, "\n");
        return metodos;
    }
}

Class Example

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;
    }
}

2 answers

5

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

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();
}
  • I tested here Miguel, did not return any method.

  • How strange... here works normally.

  • @Miguelangelo Using LINQ, how about expanding the Where() to ensure the safety of the return?

  • What do you mean? You mean I make one foreach instead of using LINQ?

  • @mgibsonbr I took the liberty of also putting the filter to remove getters/setters and other special methods.

  • 2

    I was gonna say Where(mi => mi.DeclaringType == t && !mi.IsSpecialName), but they were faster :P

  • @I think I got it... I edited it... see if that’s what you were talking about.

  • 1

    Here’s a push... congratulations on the 10k !

  • Thanks... That digit was hard, now I just want to see the next one. Maybe I’ll be alive by then! = D

Show 4 more comments

4


Use:

var m = Objeto.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).Where(x => !x.IsSpecialName).ToArray();
  • 1

    Gypsy, it worked almost right, but now he keeps showing the get methods of the class, has to filter it too?

  • 2

    @NULL If you have it, great, but if you don’t have it manually MethodInfo.isSpecialName

  • +1 for BindingFlags.DeclaredOnly... I didn’t know. I only knew with DeclaringType.

  • Thanks @mgibsonbr, I edited the Gypsy reply with this add-on you gave.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.