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:
How can I avoid the last 4 methods being returned in myMethods
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);
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.)
You also can do the trick:
var methods = typeof(MyMainClass)
.GetMethods()
.Where(m => !typeof(object)
.GetMethods()
.Select(me => me.Name)
.Contains(m.Name));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With