2012-01-03 126 views
0

我想列出基础类型中的所有方法名称。c#使用反射从底层类型获取方法名称

我试图

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

+1

什么是基础类型?什么被返回?需要更多的信息请 – user1231231412 2012-01-03 14:14:00

+3

什么的基础类型?会发生什么? “不起作用”永远不是一个好的描述。请阅读http://tinyurl.com/so-hints,并更新您的问题与更多细节。 – 2012-01-03 14:14:15

+0

更新了问题 – user49126 2012-01-03 14:21:55

回答

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

试着这么做

MethodInfo[] methodInfos = 
typeof(MyClass).GetMethods(BindingFlags.Public | 
                 BindingFlags.Static); 
+0

我需要在基类构造函数中进行此调用 – 2012-01-03 15:21:48

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

问题在于将gettype,你都在BaseClass的的构造函数调用覆盖。

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

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

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