【发布时间】:2016-02-15 03:58:24
【问题描述】:
我有几个继承自 abstract class BrowsingGoal 的类。其中一些实现了一个名为ICanHandleIntent<TPageIntent> where TPageIntent: PageIntent 的接口。
举个具体的例子:
public class Authenticate : BrowsingGoal, ICanHandleIntent<AuthenticationNeededIntent>
{
...
}
现在我想扫描 CurrentDomain 的程序集以查找所有实现 ICanHandleIntent 和 AuthenticationNeededIntent 的类型。这是我到目前为止所拥有的,但它似乎没有找到任何东西:
protected BrowsingGoal FindNextGoal(PageIntent intent)
{
// Find a goal that implements an ICanHandleIntent<specific PageIntent>
var goalHandler = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.FirstOrDefault(t => t.IsAssignableFrom((typeof (BrowsingGoal))) &&
t.GetInterfaces().Any(x =>
x.IsGenericType &&
x.IsAssignableFrom(typeof (ICanHandleIntent<>)) &&
x.GetGenericTypeDefinition() == intent.GetType()));
if (goalHandler != null)
return Activator.CreateInstance(goalHandler) as BrowsingGoal;
}
我们将不胜感激!
【问题讨论】:
-
.FirstOrDefault删除它,因为它只分析第一种类型。将其替换为.Where。如果您只想要第一个结果,请在语句末尾添加FirstOrDefault()。 -
@SteffenWinkler 不正确,
FirstOrDefault(),当提供谓词参数时,循环遍历集合并返回计算结果为 true 的第一个实例。
标签: c# generics reflection