C# Don';t返回ToString,Equals,GetHashCode,GetType with Type.GetMethods()

C# Don';t返回ToString,Equals,GetHashCode,GetType with Type.GetMethods(),c#,reflection,methods,C#,Reflection,Methods,考虑到一些类似的类: public class MyBaseClass() { public void MyMethodOne() { } public virtual void MyVirtualMethodOne() { } } public class MyMainClass : MyBaseClass() { public void MyMainClassMethod() { } public over

考虑到一些类似的类:

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
  • 托斯特林
  • 相等于
  • GetHashCode
  • GetType
如何避免在
myMethods

  • 托斯特林
  • 相等于
  • GetHashCode
  • GetType
编辑

到目前为止,这项技术正在发挥作用,但我想知道是否有更干净的方法:

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

GetMethods().Where((mi)=> mi.DeclaringType != typeof(object));
使用一点LINQ,就可以消除
对象
类中声明的所有方法。

如果使用

var myMethods = new MyMainClass().GetType().GetMethods()
    .Where(m => m.DeclaringType != typeof(object));
您将放弃那些最底层的四种方法,除非它们在您的继承权中被覆盖


(我自己也想要这种行为,但如果你想排除这四种行为,那么Cuong的回答就可以了。)

你也可以这样做:

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

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

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));
        }
公共静态IEnumerable GetMethodsWithoutStandard(此类型为t)
{
var std=new List(){nameof(ToString),
名称(等于),
名称(GetHashCode),
nameof(GetType)};
返回t.GetMethods(),其中(x=>!std.Contains(x.Name));
}

这种方法并不害怕覆盖这些方法

您可以使用这些方法只获取
MyMainClassMethod
MyVirtualMethodOne
,但我认为“声明的方法包括但不包括
对象
中的方法”没有相应的标志。这不是他想要的-这将只提供三种方法中的两种。是的,您需要使用
BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly
。(前三个是
GetMethods()
重载使用的标志。)
GetMethods()。其中((mi)=>mi.DeclaringType!=typeof(object))