我想创建基类的默认后代实例的列表。我已经可以获得的是那些后代的一个List<Type>或IEnumerable<Type>多个。
基类和后代都是自制的。所以我非常理解他们。
C# 框架是否已经为此提供了一种智能方法?
这就是我得到的:
public static List<Type> GetList_Descendants(Type baseClassType, string assemblyName)
{
return Assembly
.GetAssembly(baseClassType)
.GetTypes()
.Where(t => t.IsSubclassOf(baseClassType))
.ToList(); // Otherwise return would be of type IEnumerable.
}
public static void Add_AllDescendants<T>(this List<T> emptySource, List<Type> descendants)
where T : new()
{
emptySource.AddRange(???);
}
类的后代 && 接口
stop-cran已经给了我一个答案,关于如何获取泛型类型给出的类的后代。(请参阅下面的第一个答案和前两个评论。)
两个接口的后代
我怎样才能获得两个接口的后代?这就是我所做的,它的工作原理:
/// <summary>
/// Assumes, that there are two interfaces and classes inheriting of both - all placed in the same assembly.
/// 1st interface is IStrategy. 2nd interface is described by generic type.
///
/// Creates an IEnumerable of all available Func'IStrategy' child instances which are of generic type, too.
/// Thus one decouple creation of such a IEnumerable from creating the child classes of type IStrategy.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<Func<IStrategy>> GetByInterfaceBaseType<T>() =>
typeof(T)
.Module
.Assembly
.GetTypes()
.Where(t => (t.GetInterface(typeof(T).FullName)!= null)
&& (t.GetInterface(nameof(IStrategy)) != null))
// We assume T has a parameterless constructor
.Select(t => (Func<IStrategy>)(() => (IStrategy)Activator.CreateInstance(t)));
对我来说,这个案子已经解决了。但好的建议总是受欢迎的!
手掌心
相关分类