【发布时间】:2008-12-10 12:22:10
【问题描述】:
我想我有一个心理障碍,但有人可以告诉我如何将这两个 LINQ 语句合并为一个吗?
/// <summary>
/// Returns an array of Types that implement the supplied generic interface in the
/// current AppDomain.
/// </summary>
/// <param name="interfaceType">Type of generic interface implemented</param>
/// <param name="includeAbstractTypes">Include Abstract class types in the search</param>
/// <param name="includeInterfaceTypes">Include Interface class types in the search</param>
/// <returns>Array of Types that implement the supplied generic interface</returns>
/// <remarks>
/// History.<br/>
/// 10/12/2008 davide Method creation.<br/>
/// </remarks>
public static Type[] GetTypesImplementingGenericInterface(Type interfaceType, bool includeAbstractTypes, bool includeInterfaceTypes)
{
// Use linq to find types that implement the supplied interface.
var allTypes = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(p => p.IsAbstract == includeAbstractTypes
&& p.IsInterface == includeInterfaceTypes);
var implementingTypes = from type in allTypes
from intf in type.GetInterfaces().ToList()
where intf.FullName != null && intf.FullName.Contains(interfaceType.FullName)
select type;
return implementingTypes.ToArray<Type>();
}
我正在避免 IsAssignableFrom,因为它在不提供通用接口的特定类型时似乎会失败,因此我相信在 IsAssignableFrom 上使用 FullName caparison 就足够了,例如:
namespace Davide
{
interface IOutput<TOutputType> { }
class StringOutput : IOutput<string> { }
}
typeof(IOutput).FullName 将返回“Davide+IOutput`1”
typeof(StringOutput).GetInterfaces()[0].FullName 将返回“Davide+IOutput`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]”
因此使用 FullName.Contains 就足够了
【问题讨论】: