c#使用反射从基础类型获取方法名称

时间:2012-01-03 14:12:10

标签: c# reflection

我想列出底层类型的所有方法名称。

我试过

var methods = this.GetType().UnderlyingSystemType.GetMethods();

但不起作用。

修改

添加了示例

public class BaseClass
{
   public BaseClass()
   {
         var methods = this.GetType().UnderlyingSystemType.GetMethods();
   }
}

public class Class1:BaseClass
{
   public void Method1()
   {}

   public void Method2()
   {}
}

我需要收集方法1和方法2。

4 个答案:

答案 0 :(得分:1)

尝试类似

的内容
MethodInfo[] methodInfos =
typeof(MyClass).GetMethods(BindingFlags.Public |
                                                      BindingFlags.Static);

答案 1 :(得分:1)

您提供的代码有效。

System.Exception test = new Exception();
var methods = test.GetType().UnderlyingSystemType.GetMethods();

foreach (var t in methods)
{
    Console.WriteLine(t.Name);
}

返回

get_Message
get_Data
GetBaseException
get_InnerException
get_TargetSite
get_StackTrace
get_HelpLink
set_HelpLink
get_Source
set_Source
ToString
GetObjectData
GetType
Equals
GetHashCode
GetType

编辑:

这就是你想要的吗?

Class1 class1 = new Class1();
var methodsClass1 = class1.GetType().GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

BaseClass baseClass = new BaseClass();
var methodsBaseClass = baseClass.GetType().GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

foreach (var t in methodsClass1.Where(z => methodsBaseClass.FirstOrDefault(y => y.Name == z.Name) == null))
{
    Console.WriteLine(t.Name);
}

答案 2 :(得分:0)

here is an example on how to use reflection to get the Method names
replace MyObject with your Object / Class

using System.Reflection;
MyObject myObject;//The name of the Object
foreach(MethodInfo method in myObject.GetType().GetMethods())
 {
    Console.WriteLine(method.ToString());
 }

答案 3 :(得分:0)

问题在于覆盖您在BaseClass的构造函数中调用的GetType。

如果您创建Class1类型的实例,并查看您拥有的方法,您将看到所有6种方法。

如果您创建BaseClass类型的实例,您将只看到4个方法 - 来自Object类型的4个方法。

通过创建子类的实例,您隐式调用BaseClass中的构造函数。当它使用GetType()时,它使用Class1类型的重写虚方法,它返回预期的响应。

相关问题