简体   繁体   English

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

[英]c# get method names from underlying type using reflection

I'd like to list all method names from the underlyingtype. 我想列出底层类型的所有方法名称。

I tried 我试过了

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

but doesn't work. 但不起作用。

EDIT 编辑

Added example 添加了示例

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

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

   public void Method2()
   {}
}

I need in the collection Method1 and Method 2. 我需要在集合Method1和方法2中。

Try something like 尝试类似的东西

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

The code you provided works. 您提供的代码有效。

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

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

returns 回报

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

EDIT: 编辑:

Is that what you want? 那是你要的吗?

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

The problem lies in the override of GetType which you are calling in the constructor of the BaseClass. 问题在于覆盖您在BaseClass的构造函数中调用的GetType。

If you create an instance of the Class1 type, and look at the methods you have, you will see all 6 methods. 如果您创建Class1类型的实例,并查看您拥有的方法,您将看到所有6种方法。

If you create an instance of the BaseClass type, you will only see 4 methods - the 4 methods on from the Object type. 如果您创建BaseClass类型的实例,您将只看到4个方法 - 来自Object类型的4个方法。

By creating an instance of the subclass, you are implicitly calling the constructor in the BaseClass. 通过创建子类的实例,您隐式调用BaseClass中的构造函数。 When it uses GetType(), it uses the overridden virtual method of the Class1 type, which returns the expected response. 当它使用GetType()时,它使用Class1类型的重写虚方法,该方法返回预期的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM