C# 关于Type的一些操作(获取派生类, 获取程序域内类型, 获取特性等)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public static class TypeExtension
{
    /// 
    /// 获取程序集内所有派生类型
    /// 
    /// 
    /// 
    public static List<Type> SearchAllDerive(this Type type, Predicate<Type> match = null)
    {
        var types = Assembly.GetCallingAssembly().GetTypes();
        List<Type> ret = new List<Type>();
        foreach (var t in types)
        {
            var it = t.GetInterfaces();
            if(it.Exist(i => i.Name == type.Name && (match == null || match.Invoke(t))))
                ret.Add(t);
        }
        return ret;
    }
    /// 
    /// 获取程序集内所有派生类
    /// 
    /// 
    /// 
    public static List<Type> SearchAllDeriveClass(this Type type)
    {
        return type.SearchAllDerive(t => t.IsClass);
    }

    /// 
    /// 从程序域中指定程序集获取类型
    /// 
    /// 
    /// 
    /// 
    public static List<Type> GetTypesFromDomain(IList<string> assemblyNames, Predicate<Type> match = null)
    {
        Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies();
        var alist = ass.FindAll(a => assemblyNames.Exist(s => s == a.GetName().Name));

        var types = new List<Type>(100);

        alist.ForEach(a => types.AddRange(a.GetTypes().FindAll(match)));
        return types;
    }

    public static bool TryGetAttribute<T>(this object o, out T attr) where T : Attribute
    {
        var field = o.GetType().GetField(o.ToString());
        attr = System.Attribute.GetCustomAttribute(field!, typeof(T)) as T;
        return attr != null;
    }
}

你可能感兴趣的:(Unity,C#,c#,开发语言)