码迷,mamicode.com
首页 > 其他好文 > 详细

通过反射获取实现同一接口的所有类

时间:2019-11-19 15:32:02      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:ESS   tin   new   catch   sel   app   tty   sem   throw   

var assemblies = new List<Assembly>() { typeof(OEAppHost).Assembly };
var types = assemblies.SelectMany(x => x.GetTypes())
.Where(x => (x.GetInterfaces().Contains(typeof(ICheckOrder))))
.ToArray();

var checkOrderInstances = types.Select(x => x.CreateInstance()).ToList();

void RunNeedCheckProcess(object instance)
{
try
{
if (instance is ICheckOrder checkOrder)
checkOrder.Execute();
}
catch (Exception)
{
}
}

checkOrderInstances.ForEach(RunNeedCheckProcess);

 

static class ReflectExtension
{
public static bool HasInterface(this Type type, Type interfaceType)
{
foreach (var t in type.GetInterfaces())
{
if (t == interfaceType)
return true;
}
return false;
}
}

 

public interface ICheckOrder
{
void Execute();
}

public class CheckOrderName : ICheckOrder
{
public void Execute()
{
//throw new NotImplementedException();
}
}

 

通过反射获取实现同一接口的所有类

标签:ESS   tin   new   catch   sel   app   tty   sem   throw   

原文地址:https://www.cnblogs.com/wt-li/p/11889805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!