Do not return ToString, Equals, GetHashCode, GetType with Type.GetMethods ()

For some classes:

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'm coming back:

  • Mymethodone
  • MyVirtualMethodOne
  • MyMainClassMethod
  • Tostring
  • Equally
  • Gethashcode
  • Gettype

How can I avoid the last 4 methods returned in myMethods

  • Tostring
  • Equally
  • Gethashcode
  • Gettype

EDIT

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

  var exceptonList = new[] { "ToString", "Equals", "GetHashCode", "GetType" }; var methods = myInstanceOfMyType.GetType().GetMethods() .Select(x => x.Name) .Except(exceptonList); 
+6
source share
3 answers

You can also do the trick:

 var methods = typeof(MyMainClass) .GetMethods() .Where(m => !typeof(object) .GetMethods() .Select(me => me.Name) .Contains(m.Name)); 
+7
source

If you use

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

you will drop these bottom four methods unless they are overridden somewhere in your hierarchy.

(I would like this behavior myself, but if you want the four to exclude something, then Cuong's answer will do it.)

+8
source

Try it.

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

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

+4
source

Source: https://habr.com/ru/post/925651/


All Articles