我想获得当前程序集的某些接口的所有实现(类),并希望创建该类的实例。我怎么能这样做?
在mvc5框架中,它就像这样工作
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p) && !p.IsInterface);
但是在.net core 1.0中我该怎么做?
答案 0 :(得分:2)
获得所有实施:
/^[xX]?[0-9a-fA-F]{6}$/
要创建新对象,您需要var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p) && !p.IsInterface);
:
Activator
现在您只需要组合代码:
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
当需要使用.Net Core 1.0时,我有坏消息,不可能使用var type = typeof(IBase);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p) && !p.IsInterface);
var myObjects = new List<IBase>();
foreach (var t in types)
{
myObjects.Add((IBase)Activator.CreateInstance(t));
}
或类似的东西。请参阅:.NET Core 1.0, Enumerate All classes that implement base class