简体   繁体   中英

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

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.

We can also exclude them explicitly:

public static IEnumerable<MethodInfo> GetMethodsWithoutStandard(this Type t)
        {
            var std = new List<string>() {  nameof(ToString),
                                            nameof(Equals),
                                            nameof(GetHashCode),
                                            nameof(GetType)};
            return t.GetMethods().Where(x => !std.Contains(x.Name));
        }

This approach is not afraid of overwriting of these methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM