using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Reflection;
|
|
namespace UtilLib
|
{
|
public class MethodInfoHelper
|
{
|
public static List<MethodInfo> GetPublicMethodNames(Type type)
|
{
|
if (type == null)
|
return new List<MethodInfo>();
|
|
var methods = type.GetMethods(BindingFlags.Public |
|
BindingFlags.Instance |
|
BindingFlags.Static);
|
|
// 排除Object类的方法和事件相关方法
|
var objectMethods = typeof(Object).GetMethods(BindingFlags.Public |
|
BindingFlags.Instance |
|
BindingFlags.Static)
|
.Select(m => m.Name)
|
.ToHashSet();
|
|
// 获取所有事件
|
var events = type.GetEvents(BindingFlags.Public |
|
BindingFlags.Instance |
|
BindingFlags.Static);
|
|
// 获取所有事件相关的方法名
|
var eventMethods = events.SelectMany(e => new[]
|
{
|
$"add_{e.Name}",
|
$"remove_{e.Name}",
|
$"raise_{e.Name}"
|
}).ToHashSet();
|
|
// 过滤出带有ExportMethodAttribute注解的方法
|
return methods.Where(m => !objectMethods.Contains(m.Name) &&
|
!eventMethods.Contains(m.Name))
|
.ToList();
|
}
|
|
// 重载方法,直接传入对象实例
|
public static List<MethodInfo> GetPublicMethodNames(object obj)
|
{
|
if (obj == null)
|
throw new ArgumentNullException(nameof(obj));
|
|
return GetPublicMethodNames(obj.GetType());
|
}
|
}
|
}
|