Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't return ToString, Equals, GetHashCode, GetType with Type.GetMethods()

Given some classes like this:

public class MyBaseClass()
{
    public void MyMethodOne()
    {
    }

    public virtual void MyVirtualMethodOne()
    {
    }
}

public class MyMainClass : MyBaseClass()
{
    public void MyMainClassMethod()
    {
    }

    public override void MyVirtualMethodOne()
    {
    }
}

If I run the following:

var myMethods= new MyMainClass().GetType().GetMethods();

I get back:

  • MyMethodOne
  • MyVirtualMethodOne
  • MyMainClassMethod
  • ToString
  • Equals
  • GetHashCode
  • GetType

How can I avoid the last 4 methods being returned in myMethods

  • ToString
  • Equals
  • GetHashCode
  • GetType

EDIT

So far, this hack is working, but was wondering if there was a cleaner way:

        var exceptonList = new[] { "ToString", "Equals", "GetHashCode", "GetType" };
        var methods = myInstanceOfMyType.GetType().GetMethods()
            .Select(x => x.Name)
            .Except(exceptonList);
like image 788
Alex Avatar asked Sep 18 '12 10:09

Alex


3 Answers

If you use

var myMethods = new MyMainClass().GetType().GetMethods()
    .Where(m => m.DeclaringType != typeof(object));

you will discard those bottom four methods, unless they have been overridden somewhere in your heirarchy.

(I'd want this behaviour myself, but if you want those four excluded whatever, then Cuong's answer will do this.)

like image 145
Rawling Avatar answered Nov 15 '22 20:11

Rawling


You also can do the trick:

var methods = typeof(MyMainClass)
                    .GetMethods()
                    .Where(m => !typeof(object)
                                     .GetMethods()
                                     .Select(me => me.Name)
                                     .Contains(m.Name));
like image 10
cuongle Avatar answered Nov 15 '22 18:11

cuongle


Try this.

GetMethods().Where((mi)=> mi.DeclaringType != typeof(object));

With a little bit of LINQ, you can eliminate all the methods declared in object class.

like image 5
Madushan Avatar answered Nov 15 '22 20:11

Madushan