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

时间:2012-09-18 10:44:29

标签: c# reflection methods

鉴于这样的一些课程:

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

    public virtual void MyVirtualMethodOne()
    {
    }
}

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

    public override void MyVirtualMethodOne()
    {
    }
}

如果我运行以下内容:

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

我回来了:

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

如何避免在myMethods

中返回最后4个方法
  • 的ToString
  • 等于
  • 的GetHashCode
  • 的GetType

修改

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

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

4 个答案:

答案 0 :(得分:9)

如果您使用

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

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

(我自己也想要这种行为,但如果你想要那些被排除在外的无论,那么Cuong的回答就是这样做。)

答案 1 :(得分:8)

你也可以做到这一点:

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

答案 2 :(得分:5)

试试这个。

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

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

答案 3 :(得分:-2)

我们也可以明确地排除它们:

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

这种方法不怕重写这些方法

相关问题