[英]c# get method names from underlying type using 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()
{}
}
我需要在集合Method1和方法2中。
嘗試類似的東西
MethodInfo[] methodInfos =
typeof(MyClass).GetMethods(BindingFlags.Public |
BindingFlags.Static);
您提供的代碼有效。
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);
}
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());
}
問題在於覆蓋您在BaseClass的構造函數中調用的GetType。
如果您創建Class1類型的實例,並查看您擁有的方法,您將看到所有6種方法。
如果您創建BaseClass類型的實例,您將只看到4個方法 - 來自Object類型的4個方法。
通過創建子類的實例,您隱式調用BaseClass中的構造函數。 當它使用GetType()時,它使用Class1類型的重寫虛方法,該方法返回預期的響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.