MasstransferExporter/MasstransferCommon/Utils/AssemblyUtil.cs

49 lines
1.5 KiB
C#
Raw Normal View History

using System.Reflection;
namespace MasstransferCommon.Utils;
/// <summary>
/// 包含程序集相关的工具类
/// </summary>
public class AssemblyUtil
{
private const string Token = "masstransfer";
/// <summary>
/// 根据注解来获取类信息
/// </summary>
/// <param name="attributeType"></param>
/// <returns></returns>
public static List<Type> GetTypesByAttribute(Type attributeType)
{
return GetAssemblies()
.SelectMany(a => a.GetTypes()
.Where(t => t.GetCustomAttributes(attributeType, true).Length > 0))
.ToList();
}
private static IEnumerable<Assembly> GetAssemblies()
{
var assemblies = new List<Assembly>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var name = assembly.GetName().Name;
if (name != null && name.ToLower().Contains(Token)) GetReferenceAssemblies(assembly, assemblies);
}
return assemblies;
}
private static void GetReferenceAssemblies(Assembly assembly, ICollection<Assembly> assemblies)
{
foreach (var assemblyName in assembly.GetReferencedAssemblies())
{
var name = assemblyName.Name;
if (name == null || !name.ToLower().Contains(Token)) continue;
var ass = Assembly.Load(assemblyName);
if (assemblies.Contains(ass)) continue;
assemblies.Add(ass);
GetReferenceAssemblies(ass, assemblies);
}
}
}