不要使用Type.GetMethods()返回ToString,Equals,GetHashCode,GetType

Ale*_*lex 7 c# reflection methods

鉴于这样的一些类:

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

    public virtual void MyVirtualMethodOne()
    {
    }
}

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

    public override void MyVirtualMethodOne()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我运行以下内容:

var myMethods= new MyMainClass().GetType().GetMethods();
Run Code Online (Sandbox Code Playgroud)

我回来了:

  • MyMethodOne
  • MyVirtualMethodOne
  • MyMainClassMethod
  • 的ToString
  • 等于
  • GetHashCode的
  • 的GetType

如何避免返回最后4个方法 myMethods

  • 的ToString
  • 等于
  • GetHashCode的
  • 的GetType

编辑

到目前为止,这个黑客正在工作,但是想知道是否有更清洁的方式:

        var exceptonList = new[] { "ToString", "Equals", "GetHashCode", "GetType" };
        var methods = myInstanceOfMyType.GetType().GetMethods()
            .Select(x => x.Name)
            .Except(exceptonList);
Run Code Online (Sandbox Code Playgroud)

Raw*_*ing 9

如果你使用

var myMethods = new MyMainClass().GetType().GetMethods()
    .Where(m => m.DeclaringType != typeof(object));
Run Code Online (Sandbox Code Playgroud)

你会抛弃那些最底层的四种方法,除非它们已经在你的层次结构的某个地方被覆盖了.

(我自己也想要这种行为,但是如果你想要那四个被排除在外的东西,那么Cuong的回答就是这样做的.)


cuo*_*gle 8

你也可以做到这一点:

var methods = typeof(MyMainClass)
                    .GetMethods()
                    .Where(m => !typeof(object)
                                     .GetMethods()
                                     .Select(me => me.Name)
                                     .Contains(m.Name));
Run Code Online (Sandbox Code Playgroud)


Mad*_*han 5

试试这个.

GetMethods().Where((mi)=> mi.DeclaringType != typeof(object));
Run Code Online (Sandbox Code Playgroud)

使用一点LINQ,您可以消除object类中声明的所有方法.