C# 反射子类

C# 反射子类

反射生成子类,可以避免写一些机械代码。不用每次子类数量变更时,都要修改子类生成器的代码。

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

namespace YYX.ReflectionSomething
{
    public static class DerivedClassesFinder
    {
        public static IEnumerable<T> Find<T>()
            where T : class
        {
            var type = typeof(T);
            var tEnumerable =
                AppDomain
                .CurrentDomain
                .GetAssemblies()
                .SelectMany(assembly =>
                {
                    var types = assembly.GetTypes();
                    var findTypes = types.Where(derivedClass => derivedClass.IsSubclassOf(type) && !derivedClass.IsAbstract);
                    return findTypes.Select(derivedClass => (T)assembly.CreateInstance(derivedClass.FullName, true));
                });
            return tEnumerable;
        }
    }
}

接口也可以用类似写法

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

namespace YYX.ReflectionSomething
{
    public static class ImplementInterfaceFinder
    {
        public static IEnumerable<T> Find<T>()
        {
            var type = typeof(T);
            var tEnumerable =
                AppDomain
                .CurrentDomain
                .GetAssemblies()
                .SelectMany(assembly =>
                {
                    var types = assembly.GetTypes();
                    var findTypes = types.Where(derivedClass => derivedClass.GetInterfaces().Contains(type) && !derivedClass.IsAbstract);
                    return findTypes.Select(derivedClass => (T)assembly.CreateInstance(derivedClass.FullName, true));
                });
            return tEnumerable;
        }
    }
}

源码

下载

打赏