转自:http://www.cnblogs.com/Gxqsd/p/9759949.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FWJB_S.Test
{
class Program
{
static void Main(string[] args)
{
var helloType = typeof(Hello);
List<Type> types = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
if (helloType.IsAssignableFrom(type))
{
if (type.IsClass && !type.IsAbstract)
{
types.Add(type);
}
}
}
}
types.ForEach((t) =>
{
var helloInstance = Activator.CreateInstance(t) as Hello;
helloInstance.Say();
});
Console.ReadKey();
}
public interface Hello
{
void Say();
}
public class A : Hello
{
public void Say()
{
Console.WriteLine("Say Hello to A");
}
}
public class B : Hello
{
public void Say()
{
Console.WriteLine("Say Hello to B");
}
}
}
}
简单强大,此处假设我们要调用所有继承自Hello接口的Say方法。 类A 和 类B可以不在当前程序集,只要当前应用程序加载了它所在的程序集就行。
在我们项目分层的时候,有时候在应用层要做一些配置,但具体配置需要到不同的类库才能决定,我们应用层肯定会依赖各个类库,于是就可以在核心层创建这么一个Hello接口,各个层都会依赖于核心层(相当于公共层),各个层去实现这个Hello接口完成配置,最后我们在应用层的时候只需要查找所有继承自Hello接口的Type 创建他们的实例然后调用它们的Say方法。更多应用还等你去发现。