枚举所有继承特定接口的类

使用 Linq:
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(ISecurity))))
.ToArray();
不使用 Linq:
public static IEnumerable<Type> GetType(Type interfaceType)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
foreach (var t in type.GetInterfaces())
{
if (t == interfaceType)
{
yield return type;
break;
}
}
}
}
}

 

实例:

class Program
{
static void Main(string[] args)
{
var arr= AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(p => p.GetTypes().Where(t => t.GetInterfaces().Contains(typeof (ISignable))))
.ToArray();
Console.Read();
}
}

public interface ISignable
{

}

public class Md5Sign : ISignable
{

}
public class Base64Sign : ISignable
{

}

posted @ 2016-05-09 11:06  zslm___  阅读(702)  评论(0编辑  收藏  举报