使用反射获取 class 方法的代码(不包括系统方法,如 ToString()、Equals、Hasvalue 等。)

Code for getting the methods of a class using reflection (excluding system methods such as ToString(),Equals,Hasvalue etc..)

我正在开发一个 wcf 代理生成器,它使用 c# 动态生成所有方法。我得到以下方法,我只需要从中选择前两个。

反射中的 GetMethods() returns 我不需要的所有方法(包括 ToString、Hasvalue、Equals 等)(即我定义的实际类型)

提前致谢

如果我没理解错的话,你想要的方法是:

  • 不是 getter/setter 使用属性的方法
  • 在实际类型上定义,而不是基类型
  • 没有 return 类型的 void

    var proxyType = proxyinstance.GetType();
    var methods = proxyType.GetMethods()
        .Where(x => !x.IsSpecialName) // excludes property backing methods
        .Where(x => x.DeclaringType == proxyType) // excludes methods declared on base types
        .Where(x => x.ReturnType != typeof(void)); // excludes methods which return void
    

所有这些条件也可以组合成一个 Where 调用:

var methods = proxyType.GetMethods().Where(x => 
    !x.IsSpecialName && 
    x.DeclaringType == proxyType && 
    x.ReturnType != typeof(void)
);